如何解决如何使用 Python Selenium 点击第一个雅虎搜索结果
如何点击 Yahoo 上的第一个搜索结果?我已经尝试了所有可能的 XPATH 以及 Web 驱动程序等待方法和标准方法。但他们都没有工作。我正在使用 Python Selenium。
我的代码:
import sys
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
def element(driver,by_x,html_element):
try:
element = WebDriverWait(driver,5).until(
EC.presence_of_element_located((by_x,html_element))
)
return element
except:
print("Element not found")
def get_numbers(string):
numbers_list = [string[i] for i in range(len(string)) if string[i].isnumeric()]
number = "".join(numbers_list)
return number
class movieRatingScraper:
def __init__(self,film):
options = webdriver.ChromeOptions()
options.add_experimental_option("excludeSwitches",["enable-logging"])
self.driver = webdriver.Chrome(executable_path="./drivers/chromedriver",options=options)
self.film = film
self.driver.get(f"https://search.yahoo.com/search?p={self.film}")
def info(self):
# THE PROBLEM
element(self.driver,By.XPATH,"//*[@id='yui_3_10_0_1_1609677350466_629']").click()
def rt_rating(self):
WebDriverWait(self.driver,10).until(EC.element_to_be_clickable((By.NAME,"agree"))).click()
rt_string = element(self.driver,By.CLASS_NAME,"rottenTomatoes")
rt_rating = get_numbers(rt_string.text)
print(rt_rating)
return rt_rating
def get_current_url(self):
return self.driver.current_url
def quit(self):
self.driver.quit()
movie = movieRatingScraper("tenet")
ratings = movie.rt_rating()
movie.info()
movie.get_current_url()
解决方法
我认为您使用的 xpath 存在问题,以便单击第一个结果。请检查以下 xpath 并让我知道它是否适合您。
(//div[@id='web']/descendant::li[@class='first'])[1]/descendant::a[1]
还有一点,我相信你需要在执行 rt_rating() 之前调用下面的方法。请验证相同。
movie.info()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。