Python 如何在使用selenium使用css选择器查找后获取项目url
我试图从网页中提取一个url(链接),我使用了“通过css选择器查找元素”来获取我想要的项目。此项目中有一个url。如何提取此url 我试过:Python 如何在使用selenium使用css选择器查找后获取项目url,python,selenium,web-scraping,automation,webautomation,Python,Selenium,Web Scraping,Automation,Webautomation,我试图从网页中提取一个url(链接),我使用了“通过css选择器查找元素”来获取我想要的项目。此项目中有一个url。如何提取此url 我试过: prod_item = browser.find_elements_by_css_selector('div.col-lg-2') print(prod_item[0].get_attribute('href')) 但我的输出是“无”。我很想使用css_选择器,因为页面上有许多类似的项目,“div.col-lg-2”是所有项目的共同属性。 如何解决这个
prod_item = browser.find_elements_by_css_selector('div.col-lg-2')
print(prod_item[0].get_attribute('href'))
但我的输出是“无”。我很想使用css_选择器,因为页面上有许多类似的项目,“div.col-lg-2”是所有项目的共同属性。
如何解决这个问题并获得链接
下面是完整的代码:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
url = 'https://auctionmaxx.com/Browse?page=0'
browser = webdriver.Firefox()
browser.get(url)
prod_item = WebDriverWait(browser, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "div.col-lg-2[href]")))
print(prod_item[4].get_attribute('href'))
这一定行得通
browser.find_elements_by_css_selector('a').get_attribute('href')
代码似乎是合法的,所以首先我会尝试检查原始html源代码(使用curl或禁用JS的浏览器)。可能href属性在您试图获取其值时不包含任何url,并且该值位于其他属性中(例如在data href中),或者通过ajax动态加载。无论如何,请查看文档,或者在哪里可以找到如何等待特定内容可用的提示。要打印href属性的值,您必须导出所有元素的可见性()
- 使用
:CSS\u选择器
browser.get("https://auctionmaxx.com/Browse?page=0") prod_item = WebDriverWait(browser, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "div.col-lg-2>div a"))) print(prod_item[0].get_attribute('href'))
- 在单行中使用
:CSS\u选择器
browser.get("https://auctionmaxx.com/Browse?page=0") print(WebDriverWait(browser, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "div.col-lg-2>div a")))[0].get_attribute('href'))
- 控制台输出:
https://auctionmaxx.com/Listing/Details/321939965/NEW-PUREX-LAUNDRY-DETERGENT-924L
- 注意:您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
不会包含href
属性,但我的答案还是基于你的研究。现在,当您共享时,grand children
标记似乎包含href
属性。签出更新的答案,让我知道状态。是的,就是这样。这很好用。多谢各位much@ebere很高兴能帮助你。你觉得很有帮助。看见