【问题标题】:Beautiful soup cannot extract HTML from pages when opening links from a file从文件打开链接时,美丽的汤无法从页面中提取 HTML
【发布时间】:2018-05-24 02:51:18
【问题描述】:

我在一个文件article_links.txt 中有一些网络链接,我想一个一个地打开它们,提取它们的文本,然后打印出来。我的代码是:

import requests
from inscriptis import get_text
from bs4 import BeautifulSoup

links = open(r'C:\Users\h473\Documents\Crawling\article_links.txt', "r")

for a in links:
    print(a)
    page = requests.get(a)
    soup = BeautifulSoup(page.text, 'lxml')
    html = soup.find(class_='article-wrap')
    if html==None:
        html = soup.find(class_='mag-article-wrap')

    text = get_text(html.text)

    print(text)

但我收到一条错误消息,---> text = get_text(html.text)

AttributeError: 'NoneType' object has no attribute 'text'

所以,当我打印出 soup 变量以查看 ts 内容是什么时。这是我为每个链接找到的:

http://www3.asiainsurancereview.com//Mock-News-Article/id/42945/Type/eDaily/New-Zealand-Govt-starts-public-consultation-phase-of-review-of-insurance-law

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html><head><title>Bad Request</title>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type"/></head>
<body><h2>Bad Request - Invalid URL</h2>
<hr/><p>HTTP Error 400. The request URL is invalid.</p>
</body></html>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html><head><title>Bad Request</title>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type"/></head>
<body><h2>Bad Request - Invalid URL</h2>
<hr/><p>HTTP Error 400. The request URL is invalid.</p>
</body></html>

所以,我尝试单独从链接中提取文本,如下所示:

import requests
from inscriptis import get_text
from bs4 import BeautifulSoup

page = requests.get('http://www3.asiainsurancereview.com//Mock-News-Article/id/42945/Type/eDaily/New-Zealand-Govt-starts-public-consultation-phase-of-review-of-insurance-law')
soup = BeautifulSoup(page.text, 'lxml')
html = soup.find(class_='article-wrap')
if html==None:
    html = soup.find(class_='mag-article-wrap')
text = get_text(html.text)
print(text)

而且效果很好!因此,我尝试以列表/数组形式提供链接,并尝试从每个链接中提取文本:

import requests
from inscriptis import get_text
from bs4 import BeautifulSoup

links = ['http://www3.asiainsurancereview.com//Mock-News-Article/id/42945/Type/eDaily/New-Zealand-Govt-starts-public-consultation-phase-of-review-of-insurance-law',
'http://www3.asiainsurancereview.com//Mock-News-Article/id/42946/Type/eDaily/India-M-A-deals-brewing-in-insurance-sector',
'http://www3.asiainsurancereview.com//Mock-News-Article/id/42947/Type/eDaily/China-Online-insurance-premiums-soar-31-in-1Q2018',
'http://www3.asiainsurancereview.com//Mock-News-Article/id/42948/Type/eDaily/South-Korea-Courts-increasingly-see-65-as-retirement-age',
'http://www3.asiainsurancereview.com//Magazine/ReadMagazineArticle/aid/40847/Creating-a-growth-environment-for-health-insurance-in-Asia']

#open(r'C:\Users\h473\Documents\Crawling\article_links.txt', "r")

for a in links:
    print(a)
    page = requests.get(a)
    soup = BeautifulSoup(page.text, 'lxml')
    html = soup.find(class_='article-wrap')
    if html==None:
        html = soup.find(class_='mag-article-wrap')

    text = get_text(html.text)

    print(text)

这也很完美!那么,从文本文件中提取链接时出了什么问题?以及如何解决?

【问题讨论】:

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


    【解决方案1】:

    问题在于您的网址无效,因为它们都以换行符结尾。你可以看到同样的东西:

    >>> page = requests.get('http://www3.asiainsurancereview.com//Mock-News-Article/id/42945/Type/eDaily/New-Zealand-Govt-starts-public-consultation-phase-of-review-of-insurance-law\n')
    >>> page
    <Response [400]>
    >>> page.text
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
    <HTML><HEAD><TITLE>Bad Request</TITLE>
    <META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
    <BODY><h2>Bad Request - Invalid URL</h2>
    <hr><p>HTTP Error 400. The request URL is invalid.</p>
    </BODY></HTML>
    

    BeautifulSoup 可以很好地解析 HTML。它只是不是很有用的 HTML。而且,特别是,它没有类article-wrap 或类mag-article-wrap,所以你的find 都返回None。对于这种情况,您没有任何错误处理;您只是尝试使用 None 值,就好像它是一个 HTML 元素一样,因此例外。

    您应该在打印出每个a 时注意到这一点:每行之后都有一个额外的空白行。这要么意味着字符串中有换行符(这是实际发生的情况),要么意味着实际行之间有空行(这将是一个更加无效的 URL——你会得到一个 ConnectionError 或一些子类)。


    您想要做的很简单:只需从每一行中去掉换行符:

    for a in links:
        a = a.rstrip()
        # rest of your code
    

    【讨论】:

    • 啊!谢谢你的解释。
    【解决方案2】:

    我不知道你的文件里有什么。但在我看来,您的文件中可能有一个新的空行导致NoneType 对象

    【讨论】:

      【解决方案3】:

      试试:

      with f open("sample.txt"):
          for line in f:
              print(line)
      

      【讨论】:

      • 这如何解决问题?而且您甚至没有正确格式化代码。
      猜你喜欢
      • 2019-05-15
      • 2015-06-09
      • 1970-01-01
      • 1970-01-01
      • 2015-08-01
      • 1970-01-01
      • 2020-03-05
      • 2018-07-31
      • 1970-01-01
      相关资源
      最近更新 更多