2015-10-05 89 views
1

考慮:從lxml跨度中提取文本?

import urllib2 
from lxml import etree 

url = "http://www.ebay.com/sch/i.html?rt=nc&LH_Complete=1&_nkw=Under+Armour+Dauntless+Backpack&LH_Sold=1&_sacat=0&LH_BIN=1&_from=R40&_sop=3&LH_ItemCondition=1000" 
response = urllib2.urlopen(url) 
htmlparser = etree.HTMLParser() 
tree = etree.parse(response, htmlparser) 

其中URL是一個標準的eBay搜索結果頁面有一些過濾應用:

enter image description here

我期待例如提取的產品價格$ 40.00 $ 34.95等等

有幾個可能的XPath(如由螢火蟲提供的,XPath的檢查Firefox插件,和源的手動檢查):

/html/body/div[5]/div[2]/div[3]/div/div[1]/div/div[3]/div/div[1]/div/w-root/div/div/ul/li[1]/ul[1]/li[1]/span 
id('item3d00cf865e')/x:ul[1]/x:li[1]/x:span 
//span[@class ='bold bidsold'] 

選擇後者:

xpathselector="//span[@class ='bold bidsold']" 

tree.xpath(xpathselector)然後按預期的方式返回一個Element對象的列表。當我獲得.text屬性時,我預計會得到價格。但我得到的是:

In [17]: tree.xpath(xpathselector) 
Out[17]: 
['\n\t\t\t\t\t', 
u' 1\xc2\xa0103.78', 
'\n\t\t\t\t\t', 
u' 1\xc2\xa0048.28', 
'\n\t\t\t\t\t', 
' 964.43', 
'\n\t\t\t\t\t', 
' 922.43', 
'\n\t\t\t\t\t', 
' 922.43', 
'\n\t\t\t\t\t', 
' 275.67', 
'\n\t\t\t\t\t', 

包含在每個值看起來像價格,但(我)的價格比顯示在網頁上有什麼顯着更高,(二)我不知道什麼都換行符和標籤正在那裏做。 在嘗試提取價格時,我在這裏存在根本性錯誤嗎?

我通常使用WebDriver來處理這類事情,並利用CSS選擇器,xpath和class來查找元素。但在這種情況下,我不需要瀏覽器交互,這就是爲什麼我第一次使用urllib2lxml

回答

1

我看到2個可能:

  1. 它看起來像eBay檢查區域設置和轉換價格根據您所在的國家的貨幣。一旦你通過瀏覽器打開頁面,它可能會讀取一些瀏覽器設置,一旦你執行代碼,它可以從其他地方讀取設置。
  2. 價格可能會調整eBay使用JavaScript(客戶端),所以你不能捕捉到你的解析器。

我會建議下一檢查:

  1. 檢查你所擁有的貨幣,當你運行代碼
  2. 檢查網頁的源並確認你在瀏覽器中看到的價格也完全相同。
+0

謝謝,是仔細觀察我看到它是兩者:(i)將貨幣,以及(ii)以西班牙語將該頁面返回到urllib2。 urllib2有欺騙位置的方法嗎? – Pyderman

+0

@Pyderman嘗試檢查您的請求的樣子。找到一個工具,你可能會發現一些有關區域設置的信息。 –

1

我寫有關python

兩個例子

實施例1:

import urllib2 
from lxml import etree 

if __name__ == '__main__': 
    url = "http://www.ebay.com/sch/i.html?rt=nc&LH_Complete=1&_nkw=Under+Armour+Dauntless+Backpack&LH_Sold=1&_sacat=0&LH_BIN=1&_from=R40&_sop=3&LH_ItemCondition=1000" 
    response = urllib2.urlopen(url) 
    htmlparser = etree.HTMLParser() 
    tree = etree.parse(response, htmlparser) 
    xpathselector="//span[@class ='bold bidsold']" 
    for i in tree.xpath(xpathselector): 
     print "".join(filter(lambda x: ord(x)<64, i.text)).strip() 

實施例2:

import urllib2 
from lxml import etree 

if __name__ == '__main__': 
    url = "http://www.ebay.com/sch/i.html?rt=nc&LH_Complete=1&_nkw=Under+Armour+Dauntless+Backpack&LH_Sold=1&_sacat=0&LH_BIN=1&_from=R40&_sop=3&LH_ItemCondition=1000" 
    response = urllib2.urlopen(url) 
    htmlparser = etree.HTMLParser() 
    tree = etree.parse(response, htmlparser) 
    xpathselector="//span[@class ='bold bidsold']|//span[@class='sboffer']" 
    for i in tree.xpath(xpathselector): 
     print "".join(filter(lambda x: ord(x)<64, i.text)).strip()