python - 在python中获取一个空的XPATH表达式列表
问题描述
我在此链接上观看了视频https://www.youtube.com/watch?v=EELySnTPeyw这是代码(我已经更改了 xpath,因为网站似乎已更改)
import selenium.webdriver as webdriver
def get_results(search_term):
url = 'https://www.startpage.com'
browser = webdriver.Chrome(executable_path="D:\\webdrivers\\chromedriver.exe")
browser.get(url)
search_box = browser.find_element_by_id('q')
search_box.send_keys(search_term)
try:
links = browser.find_elements_by_xpath("//a[contains(@class, 'w-gl__result-title')]")
except:
links = browser.find_lemets_by_xpath("//h3//a")
print(links)
for link in links:
href = link.get_attribute('href')
print(href)
results.append(href)
browser.close()
get_results('cat')
该代码适用于打开浏览器并导航到搜索框和发送键的部分,但至于links
返回一个空列表,尽管我已经在开发人员工具中手动搜索了 xpath,它返回了 10 个结果。
解决方案
您需要将 keys.enter 添加到您的搜索中。你不在下一页。
search_box.send_keys(search_term+Keys.ENTER)
进口
from selenium.webdriver.common.keys import Keys
输出
https://en.wikipedia.org/wiki/Cat
https://www.cat.com/en_US.html
https://www.cat.com/
https://www.youtube.com/watch?v=cbP2N1BQdYc
https://icatcare.org/advice/thinking-of-getting-a-cat/
https://www.caterpillar.com/en/brands/cat.html
https://www.petfinder.com/cats/
https://www.catfootwear.com/US/en/home
https://www.aspca.org/pet-care/cat-care/general-cat-care
https://www.britannica.com/animal/cat