【问题标题】:How do I get href links from href using python/pandas如何使用 python/pandas 从 href 获取 href 链接
【发布时间】:2018-11-13 11:35:33
【问题描述】:

我需要获取 href 中存在的 href 链接(我已经拥有)所以我需要点击那个 href 链接并收集其他 href。我尝试过,但从该代码中只有第一个 href 得到,想要点击那个并收集前一个中存在的 href。那我怎么能这样做。 我试过了:

from bs4 import BeautifulSoup
import requests
url = 'https://www.iea.org/oilmarketreport/reports/'
page = requests.get(url)

soup = BeautifulSoup(page.text, 'html.parser')
#soup.prettify()
#table = soup.find("table")
#print(table)
links = []
for href in soup.find_all(class_='omrlist'):
    #print(href)
    links.append(href.find('a').get('href'))
print(links) 

【问题讨论】:

  • 你要么需要运行一个循环,使用 scrapy/crawling 框架来迭代遍历链接
  • 你能解释一下我这里是怎么用的吗,我之前没用过
  • 你能解释更多你的问题吗?看起来链接已经拥有你需要的所有 href 帽子。
  • 使用上面的代码我得到了href,但是如果你复制并粘贴到浏览器中,那么所有月份的链接(href),如果你点击月份名称,那么在下一页有链接名称'下载完整报告'。所以想从“下载完整报告”链接下载所有 pdf 文件并存储在数据库中

标签: python pandas beautifulsoup python-requests


【解决方案1】:

这里如何循环获取报告网址

import requests

root_url = 'https://www.iea.org'

def getLinks(url):
    all_links = []
    page = requests.get(url)
    soup = BeautifulSoup(page.text, 'html.parser')
    for href in soup.find_all(class_='omrlist'):
        all_links.append(root_url + href.find('a').get('href'))  # add prefix 'http://....'
    return all_links

yearLinks = getLinks(root_url + '/oilmarketreport/reports/')

# get report URL
reportLinks = []
for url in yearLinks:
    links = getLinks(url)
    reportLinks.extend(links)

print(reportLinks)
for url in reportLinks:
    if '.pdf' in url:
        url = url.replace('../../..', '')
        # do download pdf file
        ....
    else:
        # do extract pdf url from html and download it
        ....
    ....

现在您可以循环reportLinks 以获取 pdf 网址

【讨论】:

猜你喜欢
  • 2011-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-01
相关资源
最近更新 更多