【问题标题】:Python: find element by a hrefPython:通过href查找元素
【发布时间】:2018-10-20 08:19:18
【问题描述】:

我使用 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”。谢谢!

【问题讨论】:

    标签: python selenium web-scraping webdriver selenium-chromedriver


    【解决方案1】:

    试试下面的代码:

    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
    

    【讨论】:

    • if a_element: 绝对是多余的,好像找不到链接一样你会得到NoSuchElementException
    【解决方案2】:

    根据您提供的用于提取 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")
      

    【讨论】:

    • 一个问题,如果我想提取的不是一个href,我可以用这个找到所有具有相同专利的吗? TIA
    • @Lara19 每个&lt;a&gt; 标签将只包含一个href 属性。如果有多个 &lt;a&gt; 标签,您必须构造 Locator Strategy 以指向所需的 &lt;a&gt; 标签以检索 href 属性。如果我能回答您的反问,请告诉我。
    • 我刚刚在上面更新了它们:) 我尝试了你的代码,但发现有时它们在一页中有几个href,我只能提取一个。那你介意看看吗?谢谢
    • @Lara19 如果您的要求发生了变化,请随时根据您的新要求按照 stackoverflow 标准提出新票。 Stackoverflow 志愿者将很乐意为您提供帮助。对于这个问题,我将问题恢复到原始范围。
    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 2018-12-24
      • 2016-01-14
      • 2015-04-18
      • 2013-04-19
      • 2020-07-20
      • 2020-08-08
      • 2019-09-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多