import urllib.request
import urllib.parse
import re
from lxml import etree
def query(content):
# 请求地址
url = 'https://baike.baidu.com/item/' + urllib.parse.quote(content)
# 请求头部
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
}
# 利用请求地址和请求头部构造请求对象
req = urllib.request.Request(url=url, headers=headers, method='GET')
# 发送请求,获得响应
response = urllib.request.urlopen(req)
# 读取响应,获得文本
text = response.read().decode('utf-8')
# l = re.sub('[a-zA-Z0-9’!"#$%&\'()*+,-./:;<=>?@?★、…【】《》?“”‘’\![\\]^_`{|}~\s]+', "", text) #去除不必要的符号
# # 构造 _Element 对象
html = etree.HTML(text)
# # 使用 xpath 匹配数据,得到匹配字符串列表
sen_list = html.xpath('//div
python爬虫 爬取文本数据
最新推荐文章于 2024-05-14 18:07:14 发布