【问题标题】:Python web crawler using BeautifulSoup, trouble getting URLs使用 BeautifulSoup 的 Python 网络爬虫,获取 URL 时遇到问题
【发布时间】:2016-04-08 06:33:45
【问题描述】:

所以我正在尝试构建一个动态网络爬虫来获取链接中的所有 url 链接。 到目前为止,我能够获取章节的所有链接,但是当我尝试从每个章节中创建章节链接时,我的输出不会打印出任何内容。

我使用的代码:

#########################Chapters#######################

import requests
from bs4 import BeautifulSoup, SoupStrainer
import re


base_url = "http://law.justia.com/codes/alabama/2015/title-{title:01d}/"

for title in range (1,4): 
url = base_url.format(title=title)
r = requests.get(url)

 for link in BeautifulSoup((r.content),"html.parser",parse_only=SoupStrainer('a')):
  if link.has_attr('href'):
    if 'chapt' in link['href']:
        href = "http://law.justia.com" + link['href']
        leveltwo(href)

#########################Sections#######################

def leveltwo(item_url):
 r = requests.get(item_url)
 soup = BeautifulSoup((r.content),"html.parser")
 section = soup.find('div', {'class': 'primary-content' })
 for sublinks in section.find_all('a'):
        sectionlinks = sublinks.get('href')
        print (sectionlinks)

【问题讨论】:

    标签: python-2.7 web-scraping beautifulsoup web-crawler


    【解决方案1】:

    通过对您的代码进行一些小的修改,我能够让它运行并输出这些部分。主要是,您需要修复缩进,并在调用它之前定义一个函数。

    #########################Chapters#######################
    
    import requests
    from bs4 import BeautifulSoup, SoupStrainer
    import re
    
    def leveltwo(item_url):
        r = requests.get(item_url)
        soup = BeautifulSoup((r.content),"html.parser")
        section = soup.find('div', {'class': 'primary-content' })
        for sublinks in section.find_all('a'):
            sectionlinks = sublinks.get('href')
            print (sectionlinks)
    
    base_url = "http://law.justia.com/codes/alabama/2015/title-{title:01d}/"
    
    for title in range (1,4): 
        url = base_url.format(title=title)
        r = requests.get(url)
    
    for link in BeautifulSoup((r.content),"html.parser",parse_only=SoupStrainer('a')):
        try:
            if 'chapt' in link['href']:
                href = "http://law.justia.com" + link['href']
                leveltwo(href)
            else:
                continue
        except KeyError:
            continue
    #########################Sections#######################
    

    输出:

    /codes/alabama/2015/title-3/chapter-1/section-3-1-1/index.html /codes/alabama/2015/title-3/chapter-1/section-3-1-2/index.html /codes/alabama/2015/title-3/chapter-1/section-3-1-3/index.html /codes/alabama/2015/title-3/chapter-1/section-3-1-4/index.html etc.

    【讨论】:

    • 谢谢!我看到你做了什么。如果我为章节定义我的第一部分的函数,然后为章节“leveltwo”定义一个函数来引用第一部分,它会起作用吗?
    • 是的,如果我理解正确的话。如果两个“部分”都包含在函数中,阅读起来也会更好;)
    【解决方案2】:

    你不需要任何 try/except 块,你可以使用 href=True 和 find 或 find_all 来只选择带有 href 的锚标签或 css 选择 a[href] 如下,章节链接在第一个 ularticle 标记内,ID 为 #maincontent,因此您根本不需要过滤:

    base_url = "http://law.justia.com/codes/alabama/2015/title-{title:01d}/"
    import requests
    from bs4 import BeautifulSoup
    
    def leveltwo(item_url):
        r = requests.get(item_url)
        soup = BeautifulSoup(r.content, "html.parser")
        section_links = [a["href"] for a in soup.select('div .primary-content a[href]')]
        print (section_links)
    
    
    
    for title in range(1, 4):
        url = base_url.format(title=title)
        r = requests.get(url)
        for link in BeautifulSoup(r.content, "html.parser").select("#maincontent ul:nth-of-type(1) a[href]"):
            href = "http://law.justia.com" + link['href']
            leveltwo(href)
    

    如果您要使用 find_all,您只需传递 find_all(.., href=True) 即可过滤您的锚标签,以仅选择具有 href 的标签。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-12
      • 2017-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-17
      相关资源
      最近更新 更多