【问题标题】:Get every href from the same div in python从python中的同一个div获取每个href
【发布时间】:2018-05-28 13:32:50
【问题描述】:

我有这个汤:

该网页在网格视图(16 行 x 5 列)中有公司的引用,我想检索每个引用的 url 和标题。问题是每行中的所有 5 个引用都在一个名为 row 的类中,当我抓取页面时,我只能看到每行的第一个引用,而不是全部 5 个。到目前为止,这是我的代码:

url = 'http://www.slimstock.com/nl/referenties/'

r = requests.get(url)

soup = BeautifulSoup(r.content, "lxml")

info_block = soup.find_all("div", attrs={"class": "row"})

references = pd.DataFrame(columns=['Company Name', 'Web Page'])

for entry in info_block:
    try:

        title = entry.find('img').get('title')
        url = entry.a['href']
        urlcontent = BeautifulSoup(requests.get(url).content, "lxml")

        row = [{'Company Name': title, 'Web Page': url}]
        references = references.append(row, ignore_index=True)  

    except:
        pass 

有没有办法解决这个问题?

【问题讨论】:

    标签: python web-scraping beautifulsoup href


    【解决方案1】:

    我认为您应该遍历“img”或“a”。 你可以这样写:

    for entry in info_block:
    try:
        for a in entry.find_all("a"):
            title = a.find('img').get('title')
            url = a.get('href')
            urlcontent = BeautifulSoup(requests.get(url).content, "lxml")
            row = [{'Company Name': title, 'Web Page': url}]
            references = references.append(row, ignore_index=True)  
    except:
        pass 
    

    【讨论】:

    • 谢谢,成功了!我可以问你一些额外的事情吗,因为我对此很陌生?在页面底部有一个Show more... 选项,如果它是一个按钮类,我会使用Selenium 并说driver.findElement(By.cssSelector("input[value=\"Show more...\"]")).click();。但这种情况并非如此。它仅在 <a style> 元素中,即在 <strong> 元素内,即在 <p align> 元素内。如何抓取它以自动“点击”Show more...?提前致谢!
    • @joasa AFAIK,您现在无法执行此操作,因为您正在处理静态 html 页面。您将不得不以其他方式“按下按钮”(例如,使用 selenium)。
    • 啊,好吧,我会尝试用 Selenium 找到一种方法,尽管这些 <strong><a style> 实例让我很困惑。感谢您的帮助,干杯
    【解决方案2】:
    import pandas as pd
    from bs4 import BeautifulSoup
    import requests
    url = 'http://www.slimstock.com/nl/referenties/'
    r = requests.get(url)
    soup = BeautifulSoup(r.content, "lxml")
    info_block = soup.find_all("div", attrs={"class": "row"})
    references = pd.DataFrame(columns=['Company Name', 'Web Page'])
    
    for entry in info_block:
        anchors = entry.find_all("a")
        for a in anchors:
            try:
                title = a.find('img').get('title')
                url = a['href']
                # urlcontent = BeautifulSoup(requests.get(url).content, "lxml")
                row = [{'Company Name': title, 'Web Page': url}]
                references = references.append(row, ignore_index=True)
    
            except:
                pass
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-16
      • 2016-11-05
      • 2019-07-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-05
      • 1970-01-01
      相关资源
      最近更新 更多