京东php乱码,python - 爬取京东页面的文本为乱码

我使用beautiful soup解析京东的界面,把里面的文本全都提取出来,但是打印的时候发现全是乱码。jd的界面使用utf-8编码的,我在解码成gbk时却遇到错误。

下面是代码,请指教。

#encoding=gbk

from bs4 import BeautifulSoup

from bs4 import NavigableString

from bs4 import Comment

from bs4 import Doctype

import urllib2

def walker(soup, indent):

text=""

if soup.name is not None:

for child in soup.children:

if isinstance(child, NavigableString):

if len(child) != 1: #如何判断是否为空

text = indent + unicode(child).encode('utf-8').strip() #.decode('utf-8').encode('gbk')

text += walker(child, indent+"\t")

return text

if __name__ == "__main__":

soup = BeautifulSoup( urllib2.urlopen("http://item.jd.com/1592573020.html").read())

doctypes=soup.findAll(text=lambda text: isinstance(text, Doctype))

[doctype.extract() for doctype in doctypes]

comments = soup.findAll(text=lambda text:isinstance(text, Comment))

[comment.extract() for comment in comments]

for script in soup("script"):

script.extract()

for noscript in soup("noscript"):

noscript.extract()

for style in soup("style"):

style.extract()

text=walker(soup, "")

print "text", text.decode('utf-8').encode('gbk') #这里会出错

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
问题: python requests 爬取乱码 回答: 当使用Python的requests库爬取时,有时会遇到网乱码的问题。解决这个问题的方法有几种。一种方法是在获取网内容后,使用response.encoding属性来设置编码格式。例如,可以将response.encoding设置为'utf-8'来解决乱码问题。\[1\] 另一种方法是使用response.apparent_encoding属性来获取网的实际编码格式,然后将response.encoding设置为该编码格式。这样可以更准确地解决乱码问题。例如,可以使用response.apparent_encoding来获取网的实际编码格式,然后将response.encoding设置为该编码格式,如response.encoding = response.apparent_encoding。\[2\] 下面是一个示例代码,演示了如何使用requests库解决网乱码问题: ```python import requests url = 'https://data.stats.gov.cn/easyquery.htm?m=QueryData&dbcode=hgnd&rowcode=zb&colcode=sj&wds=%5B%5D&dfwds=%5B%5D&k1=1651977499228&h=1' headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.54 Safari/537.36 Edg/101.0.1210.39' } def solveCoding(url, headers): response = requests.get(url=url, headers=headers, verify=False) response.encoding = response.apparent_encoding print(response.json()) if __name__ == '__main__': solveCoding(url=url, headers=headers) ``` 通过使用上述代码中的方法,你可以解决Python requests库爬取乱码的问题。\[3\] #### 引用[.reference_title] - *1* *2* *3* [python 使用requests模块爬取数据时中文乱码问题](https://blog.csdn.net/weixin_48368715/article/details/124645013)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值