Python脚本来抓取html输出,有时工作,有时n

2024-09-29 21:33:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用下面的python代码从Yahoo的搜索结果中获取链接。 我使用mechanizeto作为浏览器实例,并使用beautifulsoup来解析HTML代码。在

问题是,此脚本有时工作正常,有时会引发以下错误:

WARNING:root:Some characters could not be decoded, and were replaced with REPLACEMENT CHARACTER.

很明显,它与编码和解码或gzip压缩有关,但为什么有时工作,有时不工作?怎样才能让它一直工作?在

下面是代码。运行7-8次,你会发现。在

^{pr2}$

以下是输出屏幕截图: http://pokit.org/get/img/1d47e0d0dc08342cce89bc32ae6b8e3c.jpg


Tags: 实例代码脚本链接html错误浏览器some
1条回答
网友
1楼 · 发布于 2024-09-29 21:33:55

我在一个项目中遇到了编码问题,并开发了一个函数来获取我正在抓取的页面的编码,然后您可以将您的函数解码为unicode,以尝试防止这些错误。使用re:to-compression,您需要做的是开发代码,以便在遇到压缩文件时能够处理它。在

from bs4 import BeautifulSoup, UnicodeDammit
import chardet
import re

def get_encoding(soup):
    """
    This is a method to find the encoding of a document.
    It takes in a Beautiful soup object and retrieves the values of that documents meta tags
    it checks for a meta charset first. If that exists it returns it as the encoding.
    If charset doesnt exist it checks for content-type and then content to try and find it.
    """
    encod = soup.meta.get('charset')
    if encod == None:
        encod = soup.meta.get('content-type')
        if encod == None:
            content = soup.meta.get('content')
            match = re.search('charset=(.*)', content)
            if match:
                encod = match.group(1)
            else:
                dic_of_possible_encodings = chardet.detect(unicode(soup))
                encod = dic_of_possible_encodings['encoding'] 
    return encod

处理压缩数据的链接http://www.diveintopython.net/http_web_services/gzip_compression.html

从这个问题Check if GZIP file exists in Python

^{pr2}$

相关问题 更多 >

    热门问题