冲动小郭 发表于 2020-4-1 16:26:44

python爬虫有关xpath的问题,爬虫初学者

#-*-coding:utf-8 -*-
import requests
from lxml import etree
import time #这里导入时间模块,以免豆瓣封ip

url ='https://movie.douban.com/subject/3231742/'

data = requests.get(url).text
s=etree.HTML(data)
#给定并用requests.get()方法来获取页面的text,用etree.HTML()
#来解析下载的页面数据“data”
film_name = s.xpath('//*[@id="content"]/h1/span/text()')
print("电影名:",film_name)


运行的时候总是报这个问题:
Traceback (most recent call last):
File "E:\eclipse\Python1\python1\__init__.py", line 15, in <module>
    film_name = html.xpath('//*[@id="content"]/h1/span/text()')
AttributeError: 'NoneType' object has no attribute 'xpath'

请问应该怎么解决呢?

Hello. 发表于 2020-4-1 16:42:55

https://blog.csdn.net/BeerBread134/article/details/69229527?locationNum=3&fps=1

_谪仙 发表于 2020-4-1 16:45:08

检查下你html是否为空

qiuyouzhi 发表于 2020-4-1 16:45:25

那我8成估计你是没拿到网页
打印一下data试试

suchocolate 发表于 2020-4-1 16:48:07

不加头拿不到数据
headers = {'user-agent':'firefox'}
data = requests.get(url, headers=headers).text

冲动小郭 发表于 2020-4-1 22:16:47

suchocolate 发表于 2020-4-1 16:48
不加头拿不到数据
headers = {'user-agent':'firefox'}
data = requests.get(url, headers=headers).text ...

万分感谢!我已添加,成功运行。看来还需要再认真学习了{:7_131:}

冲动小郭 发表于 2020-4-1 22:17:58

_谪仙 发表于 2020-4-1 16:45
检查下你html是否为空

感谢你的回复哦!5楼成功解决问题啦

冲动小郭 发表于 2020-4-1 22:18:57

qiuyouzhi 发表于 2020-4-1 16:45
那我8成估计你是没拿到网页
打印一下data试试

感谢回复!!已经成功运行了!

冲动小郭 发表于 2020-4-1 22:27:09

suchocolate 发表于 2020-4-1 16:48
不加头拿不到数据
headers = {'user-agent':'firefox'}
data = requests.get(url, headers=headers).text ...

额,我按你这样是成功运行了,可是还是想请问一下,这个headers是具体什么作用呢?我怎么就差这句话就不能运行呢?。。编程小白弱智提问。望海涵。。

冲动小郭 发表于 2020-4-1 22:46:57

冲动小郭 发表于 2020-4-1 22:27
额,我按你这样是成功运行了,可是还是想请问一下,这个headers是具体什么作用呢?我怎么就差这句话就不 ...

!!不好意思,不用您的解答了,我查询了有关的书了。

suchocolate 发表于 2020-4-6 12:18:36

冲动小郭 发表于 2020-4-1 22:46
!!不好意思,不用您的解答了,我查询了有关的书了。

没事,我之前回答的也不够准确。
如果不写头的话,默认user-agent是python-requests/x.x,网站一看是爬虫就拒绝了,所以应该写头。
以下是我用wireshark抓的一次requests.get在不写头的情况下发的包的内部字段,红线这里就是他的默认user-agent。https://xxx.ilovefishc.com/album/202004/06/121640znh30dsnsighvnmf.png

冲动小郭 发表于 2020-4-6 15:59:04

suchocolate 发表于 2020-4-6 12:18
没事,我之前回答的也不够准确。
如果不写头的话,默认user-agent是python-requests/x.x,网站一看是爬 ...

原来是这样!!!谢谢你非常认真和详细的解答!:D
页: [1]
查看完整版本: python爬虫有关xpath的问题,爬虫初学者