【问题标题】:Python/Selenium - how to loop through hrefs in <li>?Python/Selenium - 如何在 <li> 中循环遍历 href?
【发布时间】:2020-04-15 17:43:06
【问题描述】:

网址:https://www.ipsos.com/en-us/knowledge/society/covid19-research-in-uncertain-times

我想解析 HTML 如下:

我想获取

  • 元素和突出显示的文本中的所有 href。我试过代码
    elementList = driver.find_element_by_class_name('block-wysiwyg').find_elements_by_tag_name("li")
    for i in range(len(elementList)):
        driver.find_element_by_class_name('blcokwysiwyg').find_elements_by_tag_name("li").get_attribute("href")
    

    但该块没有返回任何内容。

    谁能帮我解决上面的代码?

  • 【问题讨论】:

      标签: python-3.x selenium-webdriver web-scraping


      【解决方案1】:

      我想它会为您获取所需的内容。

      import requests
      from bs4 import BeautifulSoup
      
      link = 'https://www.ipsos.com/en-us/knowledge/society/covid19-research-in-uncertain-times'
      
      r = requests.get(link)
      soup = BeautifulSoup(r.text,"html.parser")
      for item in soup.select(".block-wysiwyg li"):
          item_text = item.get_text(strip=True)
          item_link = item.select_one("a[href]").get("href")
          print(item_text,item_link)
      

      【讨论】:

      • 嗨@SIM,我不知道为什么 bs4 不能在我这边工作并且块返回 SSLError: HTTPSConnectionPool(host='www.ipsos.com', port=443): Max url 超出重试次数:
      • 刚才跑了,发现成功了。如果仍然遇到同样的错误,请尝试定义像 requests.get(link,headers={"User-Agent":"Mozilla/5.0"}) 这样的标头。
      • 我发现 bs4: requests.get(link, verify=False) 它会起作用
      • 感谢您的帮助!
      【解决方案2】:

      试试是这样的:

      coronas = driver.find_element_by_xpath("//div[@class='block-wysiwyg']/ul/li")
      hr = coronas.find_element_by_xpath('./a')
      print(coronas.text)
      print(hr.get_attribute('href'))
      

      输出:

      The coronavirus is touching the lives of all Americans, but race, age, and income play a big role in the exact ways the virus — and the stalled economy — are affecting people. Here's what that means.
      https://www.ipsos.com/en-us/america-under-coronavirus
      

      【讨论】:

      • 块返回错误 NoSuchElementException:消息:没有这样的元素:无法找到元素...我怀疑路径有问题?
      • @Bangbangbang 不,xpath 有效(只是再试一次)。无法解释为什么它对您不起作用。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-21
      • 2018-07-20
      • 1970-01-01
      • 1970-01-01
      • 2021-08-25
      • 2020-02-17
      • 1970-01-01
      相关资源
      最近更新 更多