【问题标题】:How can I get all the href links from a single page when web scraping using Python and Selenium?使用 Python 和 Selenium 进行网页抓取时,如何从单个页面获取所有 href 链接?
【发布时间】:2020-07-19 19:40:20
【问题描述】:

我正在做我的第一个编程项目。

我目前正在使用 XPATH 方法从网页获取链接,但是,当程序运行时它返回“[None]”。不知道为什么会发生这种情况以及如何解决这个问题。

href 链接在 html 代码中实现如下:

<div class="fixed-recipe-card__info">
        <h3 class="fixed-recipe-card__h3">
            <a href=“xyz” data-content-provider-id="" data-internal-referrer-link="rotd" class="fixed-recipe-card__title-link ng-isolate-scope" target="_self">
                <span class="fixed-recipe-card__title-link">Title</span>≠≠
            </a>
        </h3>

这是我目前尝试过的代码:

        chrome_path = '/Users/name/Downloads/chromedriver'  
        driver = webdriver.Chrome(executable_path=chrome_path)
        driver.get('https://www.website.com/')

        driver.implicitly_wait(10)
 
        # scrape for links on the page

        elems = driver.find_elements_by_xpath("//h3[@class='fixed-recipe-card__h3']")

        #store them in a list
        links = []

        for elem in elems:
        #fetch and store the links
           links.append(elem.get_attribute('href'))

        #remove the duplicates in list links [] 
        res = [i for n, i in enumerate(links) if i not in links[:n]]
        print (str(res)) 

【问题讨论】:

    标签: python xpath web-scraping selenium-chromedriver


    【解决方案1】:
    elems = driver.find_elements_by_xpath("//h3[@class="fixed-receipe-card__h3"]/a')
    

    您正在尝试获取 h3 标签而不是 a 标签的 href 属性。

    【讨论】:

    • 成功了。我应该仔细看看我在做什么。非常感谢。
    • 没有问题!您能否单击旁边的勾号以接受答案。谢谢!
    【解决方案2】:

    您也可以使用 css 选择器:

    elems = driver.find_elements_by_css_selector(".fixed-recipe-card__h3 [href]")
    links = [elem.get_attribute('href') for elem in elems]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-26
      • 1970-01-01
      • 2015-03-25
      • 1970-01-01
      • 2018-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多