[英]How to access text inside div tags using Selenium in Python?
我正在嘗試使用 Selenium 在 Python 中制作一個程序,它會打印出來自https://www.brainyquote.com/quote_of_the_day的引號
編輯:我能夠像這樣訪問引號和相關作者:
authors = driver.find_elements_by_css_selector("""div.col-xs-4.col-md-4 a[title="view author"]""")
for quote,author in zip(quotes,authors):
print('Quote: ', quote.text)
print('Author: ', author.text)
無法類似地討論主題。 正在做
total_topics = driver.find_elements_by_css_selector("""div.col-xs-4.col-md-4 a.qkw-btn.btn.btn-xs.oncl_list_kc""")
會列出不需要的清單
早些時候我使用的是 Beautiful Soup,它完美地完成了這項工作,除了 requests 庫只能訪問靜態網站。 但是,我希望能夠不斷滾動網站以繼續訪問新報價。 為此,我正在嘗試使用 Selenium。
這就是我使用 Soup 的方法:
for quote_data in soup.find_all('div', class_='col-xs-4 col-md-4'):
quote = quote_data.find('a',title='view quote').text
print('Quote: ',quote)
但是,我無法使用 Selenium 找到相同的內容。 我在 Selenium 中的基本測試代碼:
driver.maximize_window()
driver.get('https://www.brainyquote.com/quote_of_the_day')
elem = driver.find_element_by_tag_name("body")
elem.send_keys(Keys.PAGE_DOWN)
time.sleep(0.2)
quote = driver.find_element_by_xpath('//div[@title="view quote"]')
我也試過 CSS 選擇器
print(driver.find_element_by_css_selector('div.col-xs-4 col-md-4')
后者給出了 NoSuchElementFound 異常,而前者根本沒有給出任何輸出。 我很想得到一些關於我哪里出錯以及如何解決這個問題的提示。
謝謝!
quotes = driver.find_elements_by_xpath('//a[@title="view quote"]')
首先滾動到底部
您可能需要編寫某種循環來滾動並單擊引號鏈接,直到找不到更多元素為止。 這是我將如何做到這一點的一些概述:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver.get('https://www.brainyquote.com/quote_of_the_day')
while True:
# wait for all quote elements to appear
quote_links = WebDriverWait(driver, 10).until(EC.presence_of_all_elements_located((By.XPATH, "//a[@title='view quote']")))
# todo - need to check for the end condition. page has infinite scrolling
# break
# iterate the quote elements until we reach the end of this list
for quote_link in quote_links:
quote_link.click()
driver.back()
# now quote_links has gone stale because we are on a different page
quote_links = WebDriverWait(driver, 10).until(EC.presence_of_all_elements_located((By.XPATH, "//a[@title='view quote']")))
上面的代碼進入一個循環,搜索頁面上所有的“查看更多”引用鏈接。 然后,我們迭代鏈接列表並單擊每個鏈接。 此時,由於頁面不再存在, quote_links
列表中的元素已經過時,因此我們在單擊另一個鏈接之前使用WebDriverWait
重新查找元素。
這只是一個粗略的大綱,需要做一些額外的工作來確定頁面無限滾動的最終情況,並且您需要編寫操作以在報價頁面本身上執行,但希望您看到想法在這里。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.