【问题标题】:Python is filtering out currency markersPython 正在过滤掉货币标记
【发布时间】:2016-04-15 02:24:00
【问题描述】:

目标: 编写一个屏幕截图,循环浏览包含旧价格和新价格的网页选择,读取价格并将其写入 CSV 文件。

方法: 配置文件 urls.txt 包含页面列表。打开该文件并循环浏览 URL。对于每个 URL,使用 Beautiful Soup 提取“current-price”和“old-price”类的任何 div 的内容。并非所有页面都有旧价格,因此我将其设为可选。

问题: 一切正常,但有一个奇怪的例外。在价格以美元计的地方,价格和美元符号正在通过。在以欧元或英镑计价的地方,货币标记 £ 和 € 正在被剥离。我希望货币标记在所有情况下都能通过。我怀疑这是一个编码问题。 (下面的 lstrip 调用是为了删除一些错误的空格和制表符。)

urls.txt的内容:

http://uk.norton.com/norton-security-for-one-device
http://uk.norton.com/norton-security-antivirus
http://uk.norton.com/norton-security-with-backup
http://us.norton.com/norton-security-for-one-device
http://us.norton.com/norton-security-antivirus
http://us.norton.com/norton-security-with-backup
http://ie.norton.com/norton-security-for-one-device
http://ie.norton.com/norton-security-antivirus
http://ie.norton.com/norton-security-with-backup

Python 代码:

###############################################
#
# PRICESCRAPE
# Screenscraper that checks prices on PD pages
#
###############################################

# Import the modules we need
import urllib.request
import re
import lxml
from lxml import etree
from lxml.html.soupparser import fromstring
from lxml.etree import tostring
from lxml.cssselect import CSSSelector
from bs4 import BeautifulSoup, NavigableString

# Open the files we need
out = open('out.csv', 'w')
urls=open('urls.txt','r')

# function to take a URL, open the HTML, and return it
def getPage(url):
    return urllib.request.urlopen(url).read().decode(encoding='UTF-8',errors='strict').encode('ascii','ignore')

out.write('URL,Current Price,Strikethrough Price\n')



#Loop through the URLs
for url in urls:
    print('\nExamining ' + url) 
    url=url.rstrip('\n')
    html=getPage(url)
    soup = BeautifulSoup(html,'lxml')
    currentPrice = soup.find('div', {'class': 'current-price'}).contents[0].lstrip('\n').lstrip(' ').lstrip('\t')
    oldPrice = soup.find('div', {'class': 'old-price'}).contents[0].lstrip(' ')

    out.write(url)
    out.write(',')
    out.write(str(currentPrice))
    out.write(',')
    if oldPrice:
        out.write(str(oldPrice))
    else:
         out.write('No strikethrough price')
    out.write('\n')

    if html =='':
        print('Problem reading page')

print('Done. See out.csv for output')

out.close()
urls.close()

【问题讨论】:

    标签: python beautifulsoup html-parsing


    【解决方案1】:

    我会使用两个模块来使其工作并简化代码:

    • csv 将结果导出到csv 输出文件中
    • requests 让编码部分对你透明

    如果您愿意 import requests 并将 getPage 实现替换为:

    def getPage(url):
        return requests.get(url).content
    

    您也将获得带有欧元和英镑符号的价格。

    【讨论】:

      猜你喜欢
      • 2015-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-18
      • 1970-01-01
      • 2016-03-03
      • 1970-01-01
      相关资源
      最近更新 更多