import requests#获取网页模块
from bs4 import BeautifulSoup#网页解析模块
import html5lib#网页解析方法
import csv#写入表格模块
try:
kw = input('请输入需要查询的商品名:')#用户输入关键词
kv = {'user-Agent': 'Mozilla/5.0'}#模拟浏览器
url = 'https://search.jd.com/Search'#京东搜索网址
start_page=1#起始页:1
end_page=10#结束页:10
filename = kw+'.csv'#写入的表格名称
outputfile=open(filename,'w',newline='') #以写方式打开表格,取消空行
#创建一个csv.writer对象 传入一个文件句柄,默认以逗号作为分隔符
csv_writer = csv.writer(outputfile, dialect='excel')
while start_page < end_page:
wd = {'keyword':kw,'enc':'utf-8','wq':kw,'page':start_page}#参数
r = requests.get(url, params=wd, headers=kv)#链接,参数,头部
r.encoding = r.apparent_encoding
# print(r.status_code)#输出状态码
# print(r.request.headers)#输出浏览器头部信息
# print(r.request.url)#输出网址
# print(r.text[0:2000])#乱码
html= str(r.content,'utf-8')#解决乱码问题
soup = BeautifulSoup(html,'html5lib')#用html.parser解析
#搜索标签是div,属性是class:p-name 的 代码
# contents=soup.find_all('div',attrs={'class':'p-name'})
contents = soup.select('.gl-i-wrap')#选择一个笔记本的大框
for bi in contents:
bi_title = bi.select('.p-name > a > em')[0]#选择一个笔记本的标题框
if(bi_title.font):#如果有font
bi_title.font.decompose()#找到里面的font标签并删除
bi_title = bi_title.text#获取里面的内容,去除标签
print(bi_title)
bi_price = bi.select('.p-price > strong > i')[0].string#价格
print(bi_price)
bi_pingjia = bi.select('.p-commit > strong > a')[0].string#评价条数
print(bi_pingjia+'条评价')
#将商品信息写入csv文件中
csv_writer.writerow([bi_title,bi_price,bi_pingjia])
start_page +=2
except:
print("爬取失败!!!!")
python京东爬虫 保存到表格中
猜你喜欢
转载自blog.csdn.net/qq_32674347/article/details/81109121
今日推荐
周排行