【问题标题】:python3 parsing and wikipedia pagepython3解析和维基百科页面
【发布时间】:2016-03-27 22:00:21
【问题描述】:

所以我需要从“计算机科学”维基百科页面获取前 10 个链接。然后我需要为 CS 页面中的每个链接获取 10 个链接。所以我最终会有 10*10 = 100 个链接。

直到现在我写了这段代码:

import urllib.request as urllib2
html = urllib2.urlopen('https://en.wikipedia.org/wiki/Computer_science').read()
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, "lxml")


for link in soup.find_all('a', limit=10):
    rez=link.get('href')
    for i in rez.find_all('a', limit=10):
        print(i)

当我运行它时,我得到了这个错误:

“NoneType”对象没有“find_all”属性


谢谢,这很有帮助。接下来我需要从每个返回的链接中获取 10 个链接,即来自 Programming_language_theory、Computational_complexity_theory.. 等的 10 个链接。我尝试这样做:

for link in soup.find_all('a', href=True, title=True, limit=10):
        print(link['href'])
        for link2 in link['href'].find_all('a', href=True, title=True, limit=10):
            print(link2['href'])

但我收到一个错误:“str”对象没有属性“find_all”

【问题讨论】:

    标签: parsing python-3.x html-parsing wikipedia


    【解决方案1】:

    我看到的直接问题是,当我运行这个 sn-p 时,前三个项目返回:

    for link in soup.find_all('a', limit=10):
        rez=link.get('href')
        print(rez)
    

    是:

    None #mw-head #p-search

    这就是为什么当你调用 rez.find_all() 时,python 会告诉你 'NoneType' object has no attribute 'find_all'

    编辑#2:
    消除None返回并找到文章的链接和子链接的可能解决方案是:

    for link in soup.find_all('a', href=True, title=True, limit=10):
            print(link['href'])
            sub_html = urllib2.urlopen('https://en.wikipedia.org' + link['href'])
            sub_soup = BeautifulSoup(sub_html, "lxml")
            for sub_link in sub_soup.find_all('a', href=True, title=True, limit=10):
                print(sub_link['href'])
    

    出现新问题的原因是您需要为新链接创建一个新的汤对象,而link['href'] 只是一个字符串。

    【讨论】:

    • 我想要前 10 个链接,它们的内容并不重要。正因为如此,我才写了 find_all('a'),对不对?
    • 为您修改后的问题编辑
    猜你喜欢
    • 2015-05-08
    • 1970-01-01
    • 1970-01-01
    • 2011-04-22
    • 2019-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多