【问题标题】:Trouble getting the second link when the first link contains certain keyword right next to it当第一个链接旁边包含某个关键字时,无法获取第二个链接
【发布时间】:2019-02-25 20:25:05
【问题描述】:

我在 python 中创建了一个与 selenium 关联的脚本,以获取任何搜索项的第一个链接(由 duckduckgo.com 填充),除非关键字 Ad 就在该链接旁边,如下图所示。如果第一个链接包含very关键字,则脚本将获取第二个链接并退出。

我目前的搜索是 houzz

这是我的尝试(无论是否存在该关键字 Ad,它总是获得第一个链接):

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

link = "https://duckduckgo.com/?q={}&ia=web"

def get_info(driver,keyword):
    driver.get(link.format(keyword))
    for item in wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR,"h2.result__title"))):
        lead_link = item.find_element_by_css_selector("a.result__a").get_attribute("href")
        break
    print(lead_link)

if __name__ == '__main__':
    chromeOptions = webdriver.ChromeOptions()
    chromeOptions.add_argument("--headless")
    driver = webdriver.Chrome(options=chromeOptions)
    wait = WebDriverWait(driver, 10)
    try:
        get_info(driver,"*houzz*")
    finally:
        driver.quit()

如果Ad 关键字与第一个链接相邻,我该如何纠正我的脚本以获得第二个链接?

【问题讨论】:

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


    【解决方案1】:

    好像加了#links:

    lead_link = item.find_element_by_css_selector("#links a.result__a").get_attribute("href")
    

    广告位于 #ads div 内

    【讨论】:

    • 你是对的......我错过了这个。这比我的干净得多。
    【解决方案2】:

    您可以使用 XPath

    //h2[not(./span)]/a
      ^ h2 is the container for the entire link plus Ad icon
        ^ exclude h2s with SPAN children since they contain the Ad icons
                      ^ what you DO want is the A result (hyperlink)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-12
      相关资源
      最近更新 更多