简体   繁体   English

如何用循环和 selenium 解决这个问题?

[英]How to fix this problem with loops and selenium?

So I'm trying to extract the URL of the first organic search result of a certain word on Google using Selenium Web Driver and Python. So I'm trying to extract the URL of the first organic search result of a certain word on Google using Selenium Web Driver and Python. It goes like this:它是这样的:

from selenium import webdriver

chrome_options = webdriver.ChromeOptions()
driver = webdriver.Chrome(chrome_options=chrome_options)

sample =[]
news = ["a", "b", "c"]

for item in range(len(news)):
    driver.get('https://www.google.com')
    driver.find_element_by_xpath('search_bar_xpath').send_keys(news[item+1])
    driver.find_element_by_xpath('search_button_xpath').click()
    domain = driver.find_element_by_xpath('first_result_url_xpath').text
    sample.append(domain)
    driver.close()

Well, it doesn't loop.嗯,它不会循环。 Can you guys kindly help me fix it.你们能帮我解决它吗? And sometimes the first_result_url_xpath change to another name.有时 first_result_url_xpath 会更改为另一个名称。 How can I tell it to search for the other and not worry about the first try?我怎样才能告诉它搜索另一个而不用担心第一次尝试?

The problem is, that you close the driver in the first cycle of your loop.问题是,您在循环的第一个循环中关闭了驱动程序。 You should get it out from the loop:你应该把它从循环中取出:

for item in range(len(news)):
    driver.get('https://www.google.com')
    driver.find_element_by_xpath(search_bar_xpath).send_keys(news[item+1])
    driver.find_element_by_xpath(search_button_xpath).click()
    domain = driver.find_element_by_xpath(first_result_url_xpath).text
    sample.append(domain)
driver.close()

And you can get multiple result by using: driver.findElements(By.xpath(first_result_url_xpath)) and then iterate on it to find what you are searching for.您可以使用以下方法获得多个结果: driver.findElements(By.xpath(first_result_url_xpath))然后对其进行迭代以查找您要搜索的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM