目标网站http://www.piaofang.biz/
爬取页面所有电影名及票房
保存csv
import requests
from lxml import etree
import csv
url = 'http://www.piaofang.biz/'
headers = {'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Mobile Safari/537.36'}
response = requests.get(url, headers=headers)
response.encoding = 'gb2312'
data = response.text
html = etree.HTML(data)
div_tag = html.xpath('//div[@class="zhuti"]')
lst = []
for div in div_tag:
dic = {}
title = div.xpath('.//td[@class="title"]/a/text()')
piaofang = div.xpath('.//td[@class="piaofang"]/span/text()')
dic['title'] = title[0]
dic['piaofang'] = piaofang[0]
print(dic)
lst.append(dic)
运用xpath进行,每次都只能运行出来一个数据
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
2条回答 默认 最新
- qfcy_ 2022-08-08 12:45关注
原因是列表
div_tag
只有一项, 而变量title
,piaofang
有很多项。
改成这样:import requests from lxml import etree import csv url = 'http://www.piaofang.biz/' headers = {'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Mobile Safari/537.36'} response = requests.get(url, headers=headers) response.encoding = 'gb2312' data = response.text html = etree.HTML(data) div_tag = html.xpath('//div[@class="zhuti"]') div=div_tag[0] # div_tag只有一项 lst = [] dic = {} title = div.xpath('.//td[@class="title"]/a/text()') piaofang = div.xpath('.//td[@class="piaofang"]/span/text()') for t,p in zip(title,piaofang): # zip()作用是同时遍历两个列表 dic['title'] = t dic['piaofang'] = p lst.append(dic) print(dic)
如果有帮助, 点个「采纳」按钮不谢
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 3无用
悬赏问题
- ¥30 基于信创PC发布的QT应用如何跨用户启动后输入中文
- ¥20 非root手机,如何精准控制手机流量消耗的大小,如20M
- ¥15 远程安装一下vasp
- ¥15 自己做的代码上传图片时,报错
- ¥15 Lingo线性规划模型怎么搭建
- ¥15 关于#python#的问题,请各位专家解答!区间型正向化
- ¥15 unity从3D升级到urp管线,打包ab包后,材质全部变紫色
- ¥50 comsol温度场仿真无法模拟微米级激光光斑
- ¥15 上传图片时提交的存储类型
- ¥15 VB.NET如何绘制倾斜的椭圆