有一个网页,其中包含多篇文章的链接,我希望能够访问每一篇文章,并提取其中所包含的文本。为此,我使用了Helium包并编写了一个脚本,但是,我仍然遇到同样的错误。
下面是我使用过的脚本。我基本上是试图提取所有的段落标签,并创建一个Word文档从他们。但是,当我在一篇文章上测试它时,它工作得很好,但是,使用这个循环会导致我遇到指定的错误。
from helium import *
import time
from docx import Document
from docx.shared import Inches
document = Document()
start_chrome('some url', headless = True)
time.sleep(5)
article_list = find_all(S('a'))
for article in article_list:
url = article.web_element.get_attribute('href')
if url.startswith('some substring'):
go_to(url)
time.sleep(5)
paragraph_list = find_all(S('p'))
for paragraph in paragraph_list:
document.add_paragraph(paragraph.web_element.text)这是我不断犯的错误,
StaleElementReferenceException Traceback (most recent call last)
<ipython-input-10-7a524350ae24> in <module>()
1 for article in article_list:
----> 2 url = article.web_element.get_attribute('href')
3 print(url)
4 if url.startswith('some url'):
5 go_to(url)
StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
(Session info: headless chrome=86.0.4240.198)
(Driver info: chromedriver=2.38.552522 (437e6fbedfa8762dec75e2c5b3ddb86763dc9dcb),platform=Windows NT 10.0.19041 x86_64)我对网络抓取很陌生,所以我不知道是否有一些简单的东西我错过了。这里的任何帮助都将不胜感激。
发布于 2020-11-27 17:28:50
我解决了这个问题。我相信问题是我收集到的网址是在他们的亲属状态。一个更好的方法是将所有的URL收集到一个列表中,然后从那里开始,而不是通过迭代元素(文章)本身来生成它。其代码如下,
from helium import *
import time
from docx import Document
from docx.shared import Inches
document = Document()
start_chrome('some url', headless = True)
time.sleep(5)
article_list = find_all(S('a'))
href_list = [article.web_element.get_attribute('href') for article in article_list]
for href in href_list:
if href.startswith('some substring'):
go_to(href)
time.sleep(5)
paragraph_list = find_all(S('p'))
for paragraph in paragraph_list:
document.add_paragraph(paragraph.web_element.text)
document.save('Extract.docx')https://stackoverflow.com/questions/65028270
复制相似问题