- 爬虫必备包 – request
from urllib import request
- 获取数据
def get_data():
url = ' '
#创建request对象url请求头
headers = { ' user-agent' : ' ' }
req = request.Request(url, headers=headers)
#传user-agent
response = request.urlopen(req)
if response.getcode()==200: #确认是否成功
data = response.read() #读取响应的结果
data = str(data,encoding='utf-8') #转换为str
#将数据写入文件中
with open('idnex.html',mode='w',encoding='utf-8') as f:
f.write(data)
- 处理数据
data parse_data():
with open('index.html',mode='r',encoding='utf-8') as f:
html = f.read()
bs = BeautifulSoup(html,'html.parser') #使用解析器
#1.find方法,获取第一个匹配的标签
#div = bs.find('div') #找到相应的内容
#print('div') #打印相应的内容
#print(type((div)) #内容否认类型
#2.find_all方法,或取所有匹配的标签
#metas = bs.find_all('meta') #返回的是所有的集合
#print(metas[0])
#print(bs.find_all(id='hello')) #根据id 获取的数据,返回集合
#print(bs,find_all(class_='itany')) #根据class 获取
#3.获取select()方法,使用CSS选择器获取数据
#print(bs.select('#hello'))
#print(bs.select('.itany'))
#print(bs.select('p#world span'))
#print(bs.select('[title]'))
#获取文本
#print(bs.select('.div')[0].get_text())
#print(bs.find_all('article'))
value = bs.select('#article')[0].get_text(strip=Ture)
#print(len(value))
print(value)
- main函数
if name==‘main’:
parse_data()