【问题标题】:Finding a link Element in Selenium which contains a specific word in its href with python在 Selenium 中找到一个链接元素,该元素在其 href 中使用 python 包含特定单词
【发布时间】:2020-10-13 06:58:14
【问题描述】:

我是 windows 7 用户,使用 python 3.6.7chromedriver 83.3 我喜欢使用 python 实现自动化,最近开始使用 selenium 和 chromedriver 实现网络自动化。所以我对这个领域很陌生。

我写了一个脚本,可以在给它一个搜索查询之后(花几个小时在教程和文档阅读上)从互联网上下载任何软件。这是我的脚本:

from selenium import webdriver
import time
from selenium.webdriver.common.keys import Keys
import requests, bs4

query = input("Name for a windows software: ")
searchGoogle = "https://www.google.com/search?q="+"download "+str(query)+" for windows 7"

driver = webdriver.Chrome('chromedriver.exe')

links = []
website = requests.get(searchGoogle)
website_text = website.text
soup = bs4.BeautifulSoup(website_text,"lxml")
all_links = []
for link in soup.find_all("a"):
    links.append(link.get("href"))
for link in links:
    if "/url?q=" in link:
        final = link.replace("/url?q=","")
        final = final.split("&", 1)[0]
        all_links.append(final)

for ss in all_links:
    try:
        driver.get(ss)
        time.sleep(30)
        download = driver.find_element_by_partial_link_text('Download')
        download.click()
        print(download.text)
        quit()
    except:
        #print(download.href)
        print("Not Found... Moving to next...")
        continue

问题在于,有时它会点击一些显示“下载”的链接,然后转到另一个要求“开始下载”的页面。

我知道,当您下载 exe 文件时,下载链接包含如下内容:“https://something.com/something/something.exe

所以我想问一下是否有 find_element_if_its_href_contains('.exe') 或者:任何只点击一个包含“.exe”的链接的东西。

我是这个社区的新手,如果您在我的问题中发现任何不符合 StackOverflow 期望的内容,我深表歉意。在 cmets 中问我,我很乐意按照您建议的方式更改我的问题。

顺便说一句,提前致谢!

【问题讨论】:

    标签: python-3.x selenium selenium-chromedriver webautomation chrome-web-driver


    【解决方案1】:

    您可以创建一个 xpath 或 css 表达式来匹配包含字符串“.exe”的href 的 web 元素:

    driver.find_element_by_xpath("//*[contains(@href,'.exe')]")
    #or
    driver.find_element_by_css_selector("[href*='.exe']")
    

    【讨论】:

      猜你喜欢
      • 2018-08-29
      • 1970-01-01
      • 2012-09-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-14
      • 1970-01-01
      • 1970-01-01
      • 2016-07-02
      相关资源
      最近更新 更多