【问题标题】:get PDFs in iframe id="swGoogleDrive"在 iframe id="swGoogleDrive" 中获取 PDF
【发布时间】:2020-07-21 19:59:21
【问题描述】:

如何获取在此URL 的 iframe 中找到的 PDF?

(1)以下代码抛出错误。

import requests, re
from bs4 import BeautifulSoup

url = r'https://www.d88a.org/domain/102'
headers = {'User-Agent': 'C19SchoolsWebscrape'}

s = requests.Session()
r = s.get(url, headers=headers)

soup = BeautifulSoup(r.content, "lxml")
iframe_src = soup.select_one("swGoogleDrive").attrs["src"]
r = s.get(f"https:{iframe_src}")
print(r)
error: 'NoneType' object has no attribute 'attrs'

(2) 这也会引发错误。

response = requests.get(url, headers=headers)
t = re.search(b'(?<=artist":")(.*?)(?=")', response.content).group(0).decode("utf-8")
print(t)
error: 'NoneType' object has no attribute 'group'

我之前引用过的线程: Python BeautifulSoup - Scrape Web Content Inside Iframes, extract iFrame content using BeautifulSoup

【问题讨论】:

    标签: python-3.x iframe beautifulsoup lxml


    【解决方案1】:

    要获取 PDF 的所有链接,您可以使用以下示例:

    import requests
    from bs4 import BeautifulSoup
    
    
    url = 'https://www.d88a.org/domain/102'
    
    soup = BeautifulSoup(requests.get(url).content, 'html.parser')
    soup = BeautifulSoup(requests.get(soup.iframe['src']).content, 'html.parser')
    
    for a in soup.select('a'):
        print(a['href'])
    

    打印:

    https://drive.google.com/file/d/1bCXyoE7FWWI9RIcDWosHrohYQY7Ryb13/view?usp=drive_web
    https://drive.google.com/file/d/1SlR-71M-jCMF-AO4ChdSbywolIF9yL1h/view?usp=drive_web
    https://drive.google.com/file/d/1zbrt5Mnt0fZxjeD7DRYvfP6cskYKig27/view?usp=drive_web
    

    【讨论】:

    • 干杯人!我现在看到我的错误不是发出两个请求——一个用于 URL,一个用于 iframe。
    • 您能简单地告诉我href 代表什么吗?我试图理解为什么当我print(len(a['href'])) 得到84 时?目前只有 4 个 PDF。
    • @Pfalbaum a['href'] 将获得 href="..." 属性的内容。当您执行len(a['href']) 时,它将打印字符串"https://drive.google.com/file/d/1bCXyoE7FWWI9RIcDWosHrohYQY7Ryb13/view?usp=drive_web" 的长度,即84。
    • 哦,我明白了。您将如何打印链接 (PDF) 的数量?
    • 为了回答我自己的评论,我这样做是为了获取链接数:print(len(soup.select('a')))
    猜你喜欢
    • 1970-01-01
    • 2015-10-13
    • 1970-01-01
    • 2013-11-03
    • 2012-08-20
    • 2017-06-14
    • 2011-08-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多