gpt4 book ai didi

python - 属性错误 : NoneType for lxml parse getroot method

转载 作者:行者123 更新时间:2023-12-04 16:20:49 26 4
gpt4 key购买 nike

我正在尝试使用 lxml 和 mechanize 废弃一个网站,但出现错误:

AttributeError: 'NoneType' 对象没有属性 'xpath'

经过一番检查,我发现 html没有返回。

有趣的是,此代码可在其他网站上运行,但无法在此特定网站上运行 ( http://www.selangortimes.com )

url = 'http://www.selangortimes.com'
br = mechanize.Browser()
br.set_handle_robots(False)
br.set_handle_refresh(False)
br.addheaders = [('User-Agent', 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)')]
br.open(url)
resp = br.response()
html = lxml.html.parse(resp).getroot()
link_targets = [link.attrib.get('href') for link in html.xpath(expr)]

感谢你的帮助 :)

更新:
使用上述代码的工作网站示例 - http://www.themalaysianinsider.com

最佳答案

以下是您发布的代码的稍微修改版本,使用 lxml 2.3.6 Mechanize 0.2.5 产生所有 href 的列表<a> 中的属性http://www.selangortimes.com 处的元素网址。 备注 关于你的最新评论,你必须import lxml.html .

import mechanize
import lxml.html

url = 'http://www.selangortimes.com'
br = mechanize.Browser()
br.set_handle_robots(False)
br.set_handle_refresh(False)
br.addheaders = [('User-Agent', 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)')]
br.open(url)
resp = br.response()
html = lxml.html.parse(resp).getroot()
link_targets = [link.attrib.get('href') for link in html.xpath('//a')]
print(link_targets)

关于python - 属性错误 : NoneType for lxml parse getroot method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12658987/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com