Python:通过 href 查找元素



我使用网络驱动程序Chrome从网站抓取数据,但我不知道如何从href中提取数据。

.HTM:

<div class="buySearchResultContent">
<ul id="CARS_LIST_DATA">
<li class="seo_list" data-seo_name="440285">
<div class="buySearchResultContentImg">
<a href="carinfo-333285.php">
<img src="carpics/9400180056/290x200/20180305101502854_4567823.jpg" srcset="carpics/9400180056/290x200/20180305101502854_9098765.jpg 290w, carpics/9400180056/435x300/20180305101502854_00000.jpg 435w , carpics/9400180056/720x520/20180305101502854_00001.jpg 720w" sizes="(min-width: 992px) 75vw, 90vw" alt="auto">
</a>

我的代码:

driver = webdriver.Chrome("C:/chromedriver.exe")
url = "https://www.asdf.com.tw/price-02.php?v=3&brand=lisa&model=lulu&year1=2009&year2=2018&page=1"
driver.get(url)
content=driver.find_element_by_class_name('buySearchResultContentImg')
print(content)

我要提取的是"carinfo-333285.php"。谢谢!

尝试以下代码:

from selenium.common.exceptions import NoSuchElementException
try:
a_element = driver.find_element_by_xpath('//div[contains(@class, 
"buySearchResultContentImg")]/a[@href]')
link = a_element.get_attribute("href")
except NoSuchElementException:
link = None

根据您提供的用于提取href属性的 HTML,您可以使用以下任一定位器策略

  • css_selector

    myHref = driver.find_element_by_css_selector("div.buySearchResultContentImg > a").get_attribute("href")
    
  • xpath

    myHref = driver.find_element_by_xpath("//div[@class='buySearchResultContentImg']/a").get_attribute("href")
    

我对python不太了解,请尝试这个

Jpg_href= driver.find_element_by_xpath("//div[@class='buySearchResultContentImg']/a[@href='carinfo-333285.php']").get_attribute("href")

最新更新