3

我想从该站点中提取每一行中的不同标题:

https://trends.google.com/trends/trendingsearches/realtime?geo=AR&category=all

我尝试了几次没有运气的尝试。我认为通过按类搜索元素,我会得到所需的文本:

from selenium import webdriver
driver=webdriver.Chrome('path to bin')
driver.get('https://trends.google.com/trends/trendingsearches/realtime?geo=AR&category=all')
hrefs = driver.find_elements_by_class_name('title')
print hrefs
print(len(hrefs))
driver.quit()

提前谢谢各位!琼

4

2 回答 2

3

你是如此接近!您只需要从标题中获取文本,试试这个:

from selenium import webdriver

driver=webdriver.Chrome('path to bin')
driver.get('https://trends.google.com/trends/trendingsearches/realtime?geo=AR&category=all')
Titles = driver.find_elements_by_class_name('title')
for title in Titles:
    print(title.text)
driver.quit()
于 2018-06-13T16:29:47.923 回答
1

@PixelEinstein 的回答将完美地满足您的要求。但作为最佳实践的一部分,您应该始终最大化浏览器窗口并诱导WebDriverWait元素首先可见,然后提取其中的文本,如下所示:

  • 代码块:

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    options = webdriver.ChromeOptions() 
    options.add_argument("start-maximized")
    options.add_argument('disable-infobars')
    driver=webdriver.Chrome(chrome_options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
    driver.get('https://trends.google.com/trends/trendingsearches/realtime?geo=AR&category=all')
    titles = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//div[@class='title']")))
    for title in titles:
        print(title.text)
    driver.quit()
    
  • 控制台输出:

    Mauricio Macri • Cyst • Pancreas
    Abortion • National Congress of Argentina • Debate
    Abortion • Mayra Mendoza • Argentine Chamber of Deputies • Deputy
    
于 2018-06-13T16:43:49.323 回答