【问题标题】:Unable to retrieve Chinese texts while scraping抓取时无法检索中文文本
【发布时间】:2017-06-29 19:57:06
【问题描述】:

我创建了一个抓取网站:1688.com 的脚本,问题是,该网站是中文的,所以每当我尝试检索文本时,它会给我一堆 unicode,当我导出到 CSV 文件时,文件中没有任何内容。 我的代码:

# -*- coding: utf-8 -*-
import csv
from urllib import urlopen
from bs4 import BeautifulSoup as BS

csv_content = open('content.csv', 'w+')
writer_content = csv.writer(csv_content)

url = urlopen('https://fuzhuang.1688.com/nvzhuang?
spm=a260k.635.1998214976.1.7eqUGT')
html = BS(url, 'lxml')
container = html.find('ul', {'class' : 'ch-box fd-clr'})
offers = container.find_all('div', {'class' : 'ch-offer-body'})
lst = []

for offer in offers:
    offer_box = offer.find('div', {'component-name' : '@alife/ocms-
component-1688-pc-ch-offer-pic'})
    images = offer_box.find('img')['src']
    title = offer.find('div', {'class' : 'ocms-component-1688-pc-ch-offer-
title-0-1-11'}).text
    price = offer.find('div', {'class' : 'ocms-component-1688-pc-ch-offer-
price-0-1-14'}).text
    lst.append(price)

对于 lst 中的项目: writer_content.writerow([项目])

print lst 

输出是

[u'\n\n\n\xa5\n109.00\n\n\n\u6210\u4ea4\n329\n\u4ef6\n\n\n', u'\n\n\n\xa5\n56.00\n\n\n\u6210\u4ea4\n195\n\u4ef6\n\n\n', u'\n\n\n\xa5\n83.00\n\n\n\u6210\u4ea4\n109\n\u4ef6\n\n\n', u'\n\n\n\xa5\n69.00\n\n\n\u6210\u4ea4\n208\n\u4ef6\n\n\n', u'\n\n\n\xa5\n46.00\n\n\n\u6210\u4ea4\n204\n\u4ef6\n\n\n', u'\n\n\n\xa5\n45.00\n\n\n\u6210\u4ea4\n54\n\u4ef6\n\n\n', u'\n\n\n\xa5\n82.00\n\n\n\u6210\u4ea4\n38\n\u4ef6\n\n\n', u'\n\n\n\xa5\n48.90\n\n\n\u6210\u4ea4\n318\n\u4ef6\n\n\n']

我已经尝试过编码和解码 utf-8,如果你能告诉我如何解决这个问题,我将不胜感激。

【问题讨论】:

  • 如果这是您的全部代码,那么您需要使用例如写入您的 csv 文件。 writer_content.writerow。见docs.python.org/2/library/csv.html#writer-objects
  • 我已经试过了,但我忘了把那行放在上面的代码中
  • 你可以编辑答案并放上去
  • 是的,我会说的

标签: python web-scraping beautifulsoup


【解决方案1】:

此代码会将中文符号保存到txt:

对于 Python3:

         ...
(all your code above)
for i in range(len(lst)):    
    lst[i]=lst[i].replace('\n','') #getting rig of `'\n'` newlines

写入 txt:

with open(r'C:\Users\Username\list.txt','w',newline='',encoding='utf-8-sig') as f:
    for i in lst:
        f.write(i+'\t')

对于 Python2:

import unicodecsv as ucsv
with open(r'C:\Users\Username\list1.txt','wb') as f:
    w = ucsv.writer(f,encoding='utf-8-sig')
    for i in lst:
        w.writerow([i+'\t'])

【讨论】:

  • 当我尝试你的解决方案时,有一个错误提示 TypeError: 'encoding' is an invalid keyword argument for this function and the function only requires 3 arguments (4 Given)
  • 这是因为您使用的是python 2,我最初发布了python 3的解决方案。为python2添加了选项。
  • 它工作了,但无论如何我可以直接将它写入 csv 文件吗?
  • 非常感谢
猜你喜欢
  • 2022-01-18
  • 2017-01-04
  • 2021-12-25
  • 2016-04-07
  • 2020-11-10
  • 1970-01-01
  • 2022-11-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多