Skip to main content
 首页 » 编程设计

Python:通过 href 查找元素

2025年05月04日58kevingrace

我使用 webdriver 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