作者您好,weibo-follow仓库出现了selector输出为None、无法正确解析的情况,我的解决方案如下,供您参考~
报错问题: Error: 'NoneType' object has no attribute 'xpath' Traceback (most recent call last): File "D:\Code_Store\tools\weibo-follow\weibo_follow.py", line 138, in start self.get_follow_list() # 爬取微博信息 ^^^^^^^^^^^^^^^^^^^^^^ File "D:\Code_Store\tools\weibo-follow\weibo_follow.py", line 90, in get_follow_list page_num = self.get_page_num() ^^^^^^^^^^^^^^^^^^^ File "D:\Code_Store\tools\weibo-follow\weibo_follow.py", line 64, in get_page_num if selector.xpath("//input[@name='mp']") == []: ^^^^^^^^^^^^^^ AttributeError: 'NoneType' object has no attribute 'xpath'
经检查定位后发现问题原因是在使用 lxml.etree.HTML() 解析 HTML 内容时,传入的字符串包含了编码声明,而 lxml 不能直接处理这种包含编码声明的 Unicode 字符串。这可能是微博更新导致?我在两个月前使用时未发现该问题。
解决方案: lxml.etree.HTML() 需要的是字节数据,而不是字符串,修改deal_html函数如下:
def deal_html(self, url): """处理html""" try: user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36' headers = { 'User-Agent': user_agent, 'Cookie': self.cookie, 'Connection': 'close', } # 发起请求并获取响应 response = requests.get(url, headers=headers) # 使用 lxml 解析 HTML 内容,直接传递字节数据(response.content),而不是先解码为字符串 selector = etree.HTML(response.content) # 检查解析结果是否为空 if selector is None: print(f"警告: 解析页面 {url} 失败。") return None return selector
except Exception as e:
print(f"请求 {url} 时发生错误: ", e)
traceback.print_exc()
return None
替换后可以正常运行。 特别感谢作者开发的weibo_spider系列仓库,祝您工作顺利、万事如意~
感谢反馈和建议。非常好的建议,如果方便,您能否通过pull request的方式提交修改,这样会帮助到更多人,您也会成为本项目的contributor,这不是必需的。无论如何,都感谢您的热心反馈和建议。
感谢反馈和建议。非常好的建议,如果方便,您能否通过pull request的方式提交修改,这样会帮助到更多人,您也会成为本项目的contributor,这不是必需的。无论如何,都感谢您的热心反馈和建议。 感谢提醒!已使用pull request的方式提交修改