【问题标题】:I am trying to scrape the titles from the PDFs on this website. However, I get the titles and the links. Why and how can I fix this?我正在尝试从本网站上的 PDF 中抓取标题。但是,我得到了标题和链接。为什么以及如何解决这个问题?
【发布时间】:2019-10-03 17:24:28
【问题描述】:

我想在这个网站上抓取 PDF 的标题。但是,我得到了标题和链接。我该如何解决这个问题?

publications=[]
text=[]
for i in np.arange(12,19):
    response=requests.get('https://occ.ca/our- 
 publications/page/{}/'.format(i), headers={'User-Agent': 'Mozilla'})

if response.status_code == 200:
    soup = BeautifulSoup(response.text, 'lxml')
    pdfs = soup.findAll('div', {"class": "publicationoverlay"})

    links = [pdf.find('a').attrs['href'] for pdf in pdfs]
    publications.extend(links)
    text.extend(pdfs)

任何帮助将不胜感激。

【问题讨论】:

    标签: python web-scraping beautifulsoup


    【解决方案1】:

    您想要 .text 尽管拆分 \t(排除子 a 文本)并剥离。我使用Session 来提高效率。

    import requests
    from bs4 import BeautifulSoup 
    import numpy as np
    
    publications=[]
    text=[]
    
    with requests.Session() as s:
    
        for i in np.arange(12,19):
    
            response= s.get('https://occ.ca/our-publications/page/{}/'.format(i), headers={'User-Agent': 'Mozilla'})
    
            if response.status_code == 200:
                soup = BeautifulSoup(response.text, 'lxml')
                pdfs = soup.findAll('div', {"class": "publicationoverlay"})
                text.extend([pdf.text.strip().split('\t')[0] for pdf in pdfs])
    

    您还可以在获取 href 之后和获取父级的 .text 之前使用分解来删除子级标签

    import requests
    from bs4 import BeautifulSoup 
    import numpy as np
    
    publications=[]
    text=[]
    links = []
    
    with requests.Session() as s:
    
        for i in np.arange(12,19):
    
            response= s.get('https://occ.ca/our-publications/page/{}/'.format(i), headers={'User-Agent': 'Mozilla'})
    
            if response.status_code == 200:
                soup = BeautifulSoup(response.text, 'lxml')
                for a in soup.select('.publicationoverlay a'):
                    links.extend([a['href']])
                    a.decompose()
                pdfs = soup.findAll('div', {"class": "publicationoverlay"})
                text.extend([pdf.text.strip() for pdf in pdfs])
    
    print(list(zip(links, text)))
    

    【讨论】:

      猜你喜欢
      • 2017-05-30
      • 1970-01-01
      • 2014-07-06
      • 2011-04-07
      • 2022-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多