【问题标题】:How to to iterate over hrefs with selenium?如何用硒迭代hrefs?
【发布时间】:2020-08-03 09:38:50
【问题描述】:

我一直在尝试获取新闻文章主页的所有 href。最后,我想创造一些东西,给我所有新闻文章中最常用的 n 个词。为此,我认为我需要先使用 href,然后一个接一个地单击它们。

在这个平台的另一个用户的大力帮助下,这是我现在得到的代码:

from bs4 import BeautifulSoup
from selenium import webdriver

url = 'https://ad.nl'

# launch firefox with your url above
# note that you could change this to some other webdriver (e.g. Chrome)
driver = webdriver.Chrome()
driver.get(url)

# click the "accept cookies" button
btn = driver.find_element_by_name('action')
btn.click()

# grab the html. It'll wait here until the page is finished loading
html = driver.page_source

# parse the html soup
soup = BeautifulSoup(html.lower(), "html.parser")
articles = soup.findAll("article")

for i in articles:
    article = driver.find_element_by_class_name('ankeiler')
    hrefs = article.find_element_by_css_selector('a').get_attribute('href')
    print(hrefs)
driver.quit()

它给了我我认为的第一个href,但它不会遍历下一个href。它只是给我第一个 href 的次数与它必须迭代的次数一样多。有谁知道我如何让它进入下一个 href 而不是被困在第一个?

附言。如果有人对如何进一步完成我的小项目有一些建议,请随时分享,因为我还有很多关于 Python 和编程的知识要学习。

【问题讨论】:

    标签: python selenium loops web-scraping href


    【解决方案1】:

    要获取文章中的所有href,您可以这样做:

    hrefs = article.find_elements_by_xpath('//a')
    #OR article.find_element_by_css_selector('a')
    
    for href in hrefs:
      print(href.get_attribute('href'))
    

    但是,要推进项目,也许以下内容会有所帮助:

    hrefs = article.find_elements_by_xpath('//a')
    links = [href.get_attribute("href") for href in hrefs]
    
    for link in link:
      driver.get(link)
      #Add all words in the article to a dictionary with the key being the words and
      #the value being the number of times they occur
    
    

    【讨论】:

    • 这确实有效。但是有几个我不想拥有的href。我想要的hrefs都有一个名为'ankeiler__link'的类。你也许知道我怎么能只选择那些?谢谢!
    • 我已经编写了一个完整的解决方案作为另一个使用“ankeiler__link”的答案。
    【解决方案2】:

    不要用漂亮的汤,这样怎么样?

    articles = driver.find_elements_by_css_selector('article')
    
    for i in articles:
        href = i.find_element_by_css_selector('a').get_attribute('href')
        print(href)
    

    【讨论】:

      【解决方案3】:

      为了改进我之前的答案,我已经为您的问题编写了完整的解决方案:

      from selenium import webdriver
      
      url = 'https://ad.nl'
      
      #Set up selenium driver
      driver = webdriver.Chrome()
      driver.get(url)
      
      #Click the accept cookies button
      btn = driver.find_element_by_name('action')
      btn.click()
      
      #Get the links of all articles
      article_elements = driver.find_elements_by_xpath('//a[@class="ankeiler__link"]')
      links = [link.get_attribute('href') for link in article_elements]
      
      #Create a dictionary for every word in the articles
      words = dict()
      
      #Iterate through every article
      for link in links:
          #Get the article
          driver.get(link)
      
          #get the elements that are the body of the article
          article_elements = driver.find_elements_by_xpath('//*[@class="article__paragraph"]')
      
          #Initalise a empty string
          article_text = ''
      
          #Add all the text from the elements to the one string
          for element in article_elements:
              article_text+= element.text + " "
      
          #Convert all character to lower case  
          article_text = article_text.lower()
      
          #Remove all punctuation other than spaces
          for char in article_text:
              if ord(char) > 122 or ord(char) < 97:
                  if ord(char) != 32:
                      article_text = article_text.replace(char,"")
      
          #Split the article into words
          for word in article_text.split(" "):
              #If the word is already in the article update the count
              if word  in words:
                  words[word] += 1
              #Otherwise make a new entry
              else:
                  words[word] = 1
      
      #Print the final dictionary (Very large so maybe sort for most occurring words and display top 10)
      #print(words)
      
      #Sort words by most used
      most_used = sorted(words.items(), key=lambda x: x[1],reverse=True)
      
      #Print top 10 used words
      print("TOP 10 MOST USED: ")
      for i in range(10):
          print(most_used[i])
      
      driver.quit()
      

      对我来说很好,如果您遇到任何错误,请告诉我。

      【讨论】:

      • 如果我能说荷兰语,我就会明白最常用的词是什么了:)
      • 这太棒了...我唯一要补充的是,它不包括“the”“和”“a”“an”字。不过我确实有一些问题。驱动程序 get(link) 是否将驱动程序的值从 ad.nl 替换为任何链接?为什么你必须创建一个新的空字符串而不是只使用 element.text?你怎么知道 ord 必须 >122 或
      • 第一个问题的答案是肯定的,驱动程序从说“ad.nl”变为“ad.nl/article1”。第二个问题的答案是肯定的,因为每篇文章有多个段落,所以您需要将所有段落的所有文本添加在一起。我知道 ord() 必须在 122 和 97 之间,因为 (97-122 ) 是字符 a-z 的 ascii 数字。另外值得注意的是 32 是一个空格,因为我们不想删除空格,因为它们分隔了单词。您可以通过查找“ASCII 表”来获得这些数字。
      猜你喜欢
      • 2021-10-25
      • 1970-01-01
      • 2020-01-20
      • 1970-01-01
      • 1970-01-01
      • 2011-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多