Попытка перебрать hrefs с селеном - PullRequest
0 голосов
/ 20 апреля 2020

Я пытался получить все подробности домашней страницы новостной статьи. В конце я хочу создать что-то, что дало бы мне наиболее часто используемые слова из всех новостных статей. Чтобы сделать это, я решил, что сначала мне понадобятся ссылки, чтобы потом нажимать на них один за другим.

С большой помощью от другого пользователя этой платформы, вот код, который я получил прямо сейчас:

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 столько раз, сколько нужно для итерации. Кто-нибудь знает, как я могу сделать это go до следующего href вместо того, чтобы застрять на первом?

PS. если у кого-то есть какие-либо предложения относительно дальнейшей работы над моим небольшим проектом, не стесняйтесь делиться ими, поскольку у меня еще много вещей, которые нужно узнать о Python и программировании в целом.

Ответы [ 3 ]

1 голос
/ 20 апреля 2020

Вместо того, чтобы использовать красивый суп, как насчет этого?

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)
0 голосов
/ 20 апреля 2020

Чтобы улучшить мой предыдущий ответ, я написал полное решение вашей проблемы:

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()

Хорошо работает для меня, дайте мне знать, если у вас возникнут ошибки.

0 голосов
/ 20 апреля 2020

Чтобы получить все ссылки в статье, вы можете сделать:

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

...