【问题标题】:Scraped texts saved in a variable returns only the last text保存在变量中的抓取文本仅返回最后一个文本
【发布时间】:2022-01-17 10:46:07
【问题描述】:

我正在使用 selenium 从新闻网站的第一页抓取有关给定关键字的所有文章。代码如下:

homepage = "https://duckduckgo.com/?q=site%3Awww.ilgiornale.it+immigrati&t=h_&ia=web"
driver.get(homepage)
links_giornale = driver.find_elements(By.XPATH, "//a[@class='result__a js-result-title-link']")
hrefs_giornale = []
for link in links_giornale[1:]:
    pages = link.get_attribute("href")
    hrefs_giornale.append(pages)

#to accept cookies the first time I access the website
driver.get(hrefs_giornale[0])
driver.find_element(By.XPATH, "//button[@mode='primary']").click()

for href in hrefs_giornale:
    driver.get(href)
    element = driver.find_elements(By.XPATH, "//div[@class='content__body typography']")
    for art in element:
        print(art.text)

在最后一行,如果我打印 art.text,它会正确打印从第一个网页抓取的所有文章,但如果我将文本保存在变量中或将所有文本附加到列表中,它只会返回最后一篇文章.我尝试在变量中使用 art.text ,使用列表理解并使用 append() 但结果总是相同的。你能帮我理解问题是什么吗?因为我需要操纵所有这些文本。谢谢!

【问题讨论】:

    标签: python selenium web-scraping xpath environment-variables


    【解决方案1】:

    试试这样的

    all_texts = []
    
    for href in hrefs_giornale:
        driver.get(href)
        element = driver.find_elements(By.XPATH, "//div[@class='content__body typography']")
        for art in element:
            all_texts.append(art.text)
    
    for t in all_texts:
        print(t)
    

    https://www.kite.com/python/answers/how-to-add-a-string-to-a-list-as-an-element-in-python

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-25
      • 1970-01-01
      相关资源
      最近更新 更多