如何解析差距?

时间:2014-03-02 08:55:34

标签: python xpath python-3.x lxml

请帮助从易趣页面获取价格。

在以下脚本中,我从两个特定页面获取价格。

import pprint
import requests
import lxml.etree
import lxml.html
import lxml.cssselect
import re


def get_doc(url):
    try:
        req = requests.get(url)
    except Exception:
        print('Error open. __', Exception)
    else:
        html = req.text
        doc = lxml.html.document_fromstring(html)
        return doc


for url in ['http://www.ebay.com/itm/DW-PDP-Concept-Pearlescent-White-Maple-Drumset-/121271668104?pt=US_Drums&hash=item1c3c5acd88', 'http://www.ebay.com/itm/LOT-OF-20-DRUM-SET-TUNING-KEYS-DW-TAMA-PEARL-SABIAN-and-OTHER-UNIQUE-KEYS-/291092068092?pt=US_Drums&hash=item43c67076fc']:
    doc = get_doc(url)
    title = doc.xpath('//h1[@id="itemTitle"]/text()')
    priceUSD = doc.xpath('//span[@itemprop="price"]/text()')
    print(title, priceUSD)
问题是第一页的价格有一个空格('& _n_b_s_p_;')。因此得到错误的xpath值text()。它看起来如下:

  

['DW / PDP Concept Pearlescent White Maple Drumset'] ['US $ 1 \ xa0200,00']   ['很多20个鼓组调节键! DW! TAMA!珍珠! SABIAN!和别的   UNIQUE KEYS !!'] ['US $ 6,05']

P.S。 它没有正确的价格:'US $ 1 \ xa0200,00'

1 个答案:

答案 0 :(得分:1)

替换\xa0

priceUSD = [t.replace('\xa0', '') for t in
            doc.xpath('//span[@itemprop="price"]/text()')]

BTW,我得到了以下输出而没有修改:

['DW/PDP Concept Pearlescent White Maple Drumset'] ['US $1,200.00']
['LOT OF 20 DRUM SET TUNING KEYS! DW! TAMA! PEARL! SABIAN! and OTHER UNIQUE KEYS!!'] ['US $6.05']