版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
一、 网络采集的一般流程
1.通过网站域名获取HTML数据
#1.requests方法
import requests
url="http://www.runoob.com/html/html-intro.html" #1.请求地址
r=requests.get(url) #2.发送请求
html=r.text.encode(r.encoding).decode() #3.将读取的数据转为二进制,然后解码
html[:10]
#2.urllib方法
from urllib import request
url="http://www.runoob.com/html/html-intro.html" #1.请求地址
html=request.urlopen(url).read() #2.打开网页,读取网页
html.decode() #3.让网页内容解码
2.根据目标信息解析数据
#利用BeautifulSoup解析html文档
import requests
from bs4 import BeautifulSoup
url="http://www.runoob.com/html/html-intro.html" #1.请求地址
html=r.text.encode(r.encoding).decode() r=requests.get(url)
soup=BeautifulSoup(html,"lxml")
#-------------------二、提取信息---------------------
soup.head #获取head信息
soup.body #获取body 信息
soup.body.h1 #获取body 中的第一个h1标记信息
soup.findAll("h2") #获取html 中的所有h2标记信息
3.存储目标数据
#3.存储目标数据
import requests
from bs4 import BeautifulSoup
url="http://www.runoob.com/html/html-intro.html" #1.请求地址
r=requests.get(url) #2.发送请求
html=r.text.encode(r.encoding).decode() #3.解码
soup=BeautifulSoup(html,"lxml") #4.将获取的内容变成一个具体的对象
import pandas as pd
l=[x.text for x in soup.findAll("h2")] #1.读取获取html 中的所有h2标记 2.提取文字消息放入列表
df=pd.DataFrame(l,columns=[url]) #2.将数据列表信息+对应的列名转换为表格形式
#-----------------------????????????----------------------------------------
df.iloc[2,0] #获取对应的值
df.to_excel("爬虫.xlsx") #3.将表格命名,转换为excel格式
df.to_csv("爬虫.csv")
4.若有必要,移到另一个网页重复这个过程
import requests
from bs4 import BeautifulSoup
import pandas as pd
#----------------------一.通过网站域名获取HTML数据----------------------------------------
#1.
url="http://www.runoob.com/html/html-intro.html" #1.请求地址
r=requests.get(url) #2.发送请求
html=r.text.encode(r.encoding).decode() #3.解码
soup=BeautifulSoup(html,"lxml") #4.将获取的内容变成一个具体的对象
#----------------------二、所有满足链接的集合------------------------------------------------
links =[i for i in soup.findAll("a") #找到所有的a标签
if i.has_attr("href") and i.attrs["href"][0:5]=="/html"] #a标签满足有href且链接前面的字符串为"/html"
relative_urls =set(i.attrs["href"] for i in links) #1.转化为字典 2.取对应的链接 3.转化为集合去重
absolute_urls ={"http://www.runoob.com"+i for i in relative_urls} #每一个链接加上绝对路径
absolute_urls.discard(url) #去重url:如果存在删除,不存在不影响
#----------------------三、循环读取链接集合中的文本的内容----------------------------------
df=pd.DataFrame([],columns=[]) #定义表格格式
for i in absolute_urls: #遍历集合
ri=requests.get(i) #发出请求
soupi=BeautifulSoup(ri.text.encode(ri.encoding).decode(),"lxml") #读取网页内容转化为soup对象
li=[x.text for x in soupi.findAll("a")] #找到此页面所有的a标签的文本
dfi=pd.DataFrame(li,columns=[i]) #将网页内容和网址对应显示
df =df.join(dfi,how ="outer") #将其加入到原来的表格
#----------------------四、循环读取链接集合中的文本的内容----------------------------------
df.to_csv("爬虫.csv")