问题描述
我正在学习网络抓取并安装了 requests-html
。现在我运行了我在教程中看到的这个脚本,但无法让它工作。我不明白,因为它是标准库的一部分。我试过 pip install email
但它只是返回另一个错误:
我在 shell 中运行了代码,chromium
已按预期安装用于 render()
函数。 pyppeteer
由于某种原因超时,所以我不得不声明 html.render(timeout=60)
,然后它可以工作,但如果我使用脚本而不是 IDLE shell,我仍然无法让它工作。
这是下面的代码:
from requests_html import HTMLSession
session = HTMLSession()
url = 'https://www.youtube.com/channel/UC8tgRQ7DOzAbn9L7zDL8mLg/videos'
r = session.get(url)
r.html.render(sleep=1,keep_page=True,scrolldown=1)
#take the rendered html and find the element that we are interested in
videos = r.html.find('#video-title')
#loop through those elements extracting the text and link
for item in videos:
video = {
'title': item.text,'link': item.absolute_links
}
print(video)
这是回溯:
Traceback (most recent call last):
File "D:/Python/requests-render-demo.py",line 1,in <module>
from requests_html import HTMLSession
File "C:\python39\lib\site-packages\requests_html.py",line 9,in <module>
import pyppeteer
File "C:\python39\lib\site-packages\pyppeteer\__init__.py",line 15,in <module>
from importlib_Metadata import version
File "C:\python39\lib\site-packages\importlib_Metadata\__init__.py",line 7,in <module>
import email
File "D:/Python\email.py",in <module>
import smtplib
File "C:\python39\lib\smtplib.py",line 47,in <module>
import email.utils
ModuleNotFoundError: No module named 'email.utils'; 'email' is not a package ```
解决方法
看起来您面临的问题是:
...如果我使用脚本而不是 IDLE shell,我仍然无法让它工作...
从堆栈跟踪来看,似乎 requests_html
没有正确安装(回溯表明它无法导入 requests_html
)
假设您正在运行一个全新的虚拟环境,请再次安装该库,然后在虚拟环境中试用您的脚本:
virtualenv new_virtual_environment
source new_virtual_environment/bin/activate # This will enable the virtual environemnt
pip install requests-html
python <<path_to_script file>>