【问题标题】:Isolating a link with beautifulsoup用 beautifulsoup 隔离链接
【发布时间】:2023-01-30 13:14:26
【问题描述】:

我必须抓取一个网站的文本:link。我使用页面上所有链接的 beautifulsoup 创建了一个集合,然后最终我想遍历该集合。

import requests
from bs4 import BeautifulSoup


url = 'https://crmhelpcenter.gitbook.io/wahi-digital/getting-started/readme'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
links = soup.find_all('a')
check = []
for link in links:
    link = 'https://crmhelpcenter.gitbook.io' + link.get('href')
    check.append(link)
print(check)

使用这种方法,它不会在侧边栏中添加某些链接的子链接。我可以遍历每个页面并相应地添加链接,但是我必须再次遍历每个链接并检查它是否包含在一个集合中,这使得时间变得昂贵。有什么办法可以让我只隔离每个页面上的“下一个”链接并递归地完成它直到我到达终点吗?

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    有什么办法可以让我只隔离每个页面上的“下一个”链接并递归地完成它直到我到达终点吗?

    如果你的意思是像这样的按钮

    OR

    那么您可以查找带有data-rnwi-handle="BaseCard"a标签和[因为“上一个”按钮具有相同的属性]包含“下一个”作为第一个[stripped] string(参见下面的aNxt)。您不一定需要使用递归 - 因为每个页面只有一个“下一页”[最多],while 循环就足够了:

    # from urllib.parse import urljoin # [ if you use it ]
    
    rootUrl = 'https://crmhelpcenter.gitbook.io'
    nxtUrl = f'{rootUrl}/wahi-digital/getting-started/readme'
    nextUrls = [nxtUrl]
    # allUrls = [nxtUrl] # [ if you want to collect ]
    while nxtUrl:
        resp = requests.get(nxtUrl)
        print([len(nextUrls)], resp.status_code, resp.reason, 'from', resp.url)
        soup = BeautifulSoup(resp.content, 'html.parser')
    
        ### EXTRACT ANY PAGE DATA YOU WANT TO COLLECT ###
        # pgUrl = {urljoin(nxtUrl, a["href"]) for a in soup.select('a[href]')}
        # allUrls += [l for l in pgUrl if l not in allUrls]
    
        aNxt = [a for a in soup.find_all(
            'a', {'href': True, 'data-rnwi-handle': 'BaseCard'}
        ) if list(a.stripped_strings)[:1]==['Next']]
        
        # nxtUrl = urljoin(nxtUrl, aNxt[0]["href"]) if aNxt else None
        nxtUrl = f'{rootUrl}{aNxt[0]["href"]}' if aNxt else None
        nextUrls.append(nxtUrl) # the last item will [most likely] be None
    # if nxtUrl is None: nextUrls = nextUrls[:-1] # remove last item if None
    

    在 colab 上,这需要大约 3 分钟的时间来运行并收集nextUrls 中的 344[+1 for None] 项目和allUrls 中的 2879 项;省略或保留 allUrls 在此期间似乎没有任何显着差异,因为大部分延迟是由于请求(以及一些由于解析)造成的。

    你也可以尝试刮全部~3k 链接this queue-based crawler。 [在我的 colab notebook 上花了大约 15 分钟。] 结果以及 nextUrlsallUrls 已上传到this spreadsheet.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-08
      • 1970-01-01
      • 2021-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-08
      • 1970-01-01
      相关资源
      最近更新 更多