【问题标题】:I am getting error in web scraping using python beautifulsoup我在使用 python beautifulsoup 进行网络抓取时遇到错误
【发布时间】:2016-08-18 22:46:48
【问题描述】:

我收到以下错误。

Traceback (most recent call last):File "ex1.py", line 9, in <module>
    print(soup.prettify())
  File "C:\Python34\lib\encodings\cp437.py", line 19, in encodereturn
    codecs.charmap_encode(input,self.errors,encoding_map)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position35013: character maps to <undefined>

我的源代码如下:

import requests
from bs4 import BeautifulSoup

url = 'http://www.yellowpages.com/search?search_terms=coffee&geo_location_terms=Los+Angeles%2C+CA'
response = requests.get(url)
html = response.content

soup = BeautifulSoup(html, "html.parser")
print(soup.prettify())

【问题讨论】:

    标签: python beautifulsoup python-requests


    【解决方案1】:

    更改为我的作品

    html = response.text
    soup = BeautifulSoup(html)
    print soup.prettify()
    

    【讨论】:

    • 不,这仍然不适合我。我想获取所有的 html 内容,而不仅仅是文本。
    【解决方案2】:

    您是否在 Windows 上运行此程序?原因是您的 html 内容的编码问题。

    我认为这可能有效:

    import requests
    from bs4 import BeautifulSoup
    
    url = 'http://www.yellowpages.com/search?search_terms=coffee&geo_location_terms=Los+Angeles%2C+CA'
    response = requests.get(url)
    html = response.content
    
    soup = BeautifulSoup(html, "html.parser")
    print(soup.prettify().encode('UTF-8'))
    

    prettify() 上传递编码参数也应该有效。像这样:

    soup.prettify(encoding='utf-8')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-18
      • 2018-05-30
      • 2020-10-04
      • 2021-01-31
      • 1970-01-01
      • 1970-01-01
      • 2022-12-10
      • 1970-01-01
      相关资源
      最近更新 更多