在python中解析xml不理解DOM

2024-09-29 23:21:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经读了一整天关于用python解析xml的文章,但是看看我需要提取数据的站点,我不确定我是不是找错了树。基本上我想从超市网站(在图片名称中找到)得到13位的条形码。例如:

http://www.tesco.com/groceries/SpecialOffers/SpecialOfferDetail/Default.aspx?promoId=A31033985

有11个项目和11个图像,第一个项目的条形码是0000003235676。然而,当我查看页面源代码时(我假设这是使用python、urllib和beauthoulsoup一次性提取所有条形码的最佳方法),所有的条形码都在一行(第12行),但是数据在元素和属性方面似乎不像我预期的那样结构化。在

    new TESCO.sites.UI.entities.Product({name:"Lb Mens Mattifying Dust 7G",xsiType:"QuantityOnlyProduct",productId:"275303365",baseProductId:"72617958",quantity:1,isPermanentlyUnavailable:true,imageURL:"http://img.tesco.com/Groceries/pi/805/5021320051805/IDShot_90x90.jpg",maxQuantity:99,maxGroupQuantity:0,bulkBuyLimitGroupId:"",increment:1,price:2.5,abbr:"g",unitPrice:3.58,catchWeight:"0",shelfName:"Mens Styling",superdepartment:"Health & Beauty",superdepartmentID:"TO_1448953606"});
new TESCO.sites.UI.entities.Product({name:"Lb Mens Thickening Shampoo 250Ml",xsiType:"QuantityOnlyProduct",productId:"275301223",baseProductId:"72617751",quantity:1,isPermanentlyUnavailable:true,imageURL:"http://img.tesco.com/Groceries/pi/225/5021320051225/IDShot_90x90.jpg",maxQuantity:99,maxGroupQuantity:0,bulkBuyLimitGroupId:"",increment:1,price:2.5,abbr:"ml",unitPrice:1,catchWeight:"0",shelfName:"Mens Shampoo ",superdepartment:"Health & Beauty",superdepartmentID:"TO_1448953606"});
new TESCO.sites.UI.entities.Product({name:"Lb Mens Sculpting Puty 75Ml",xsiType:"QuantityOnlyProduct",productId:"275301557",baseProductId:"72617906",quantity:1,isPermanentlyUnavailable:true,imageURL:"http://img.tesco.com/Groceries/pi/287/5021320051287/IDShot_90x90.jpg",maxQuantity:99,maxGroupQuantity:0,bulkBuyLimitGroupId:"",increment:1,price:2.5,abbr:"ml",unitPrice:3.34,catchWeight:"0",shelfName:"Pastes, Putty, Gums, Pomades",superdepartment:"Health & Beauty",superdepartmentID:"TO_1448953606"});

也许像Beauthulsoup这样的东西太过分了?我知道DOM树和原始源代码是不一样的,但为什么它们如此不同-当我在firefox中检查元素时,数据看起来像我预期的那样结构化。在

如果你觉得这完全是愚蠢的,请道歉,谢谢。在


Tags: 数据namecomhttpuinewproductsites
2条回答

由于您的站点使用javascript来格式化其内容,您可能会发现从urllib切换到Selenium这样的工具非常有用。这样你就可以抓取网页,因为他们呈现给一个真正的用户与网络浏览器。这个github project似乎解决了您的任务。在

另一种选择是从页面javascript脚本中过滤出json数据,然后直接从中获取数据。在

不幸的是,条形码在HTML中不是作为结构化数据给出的;它只是作为URL的一部分嵌入的。因此,我们需要隔离URL,然后使用字符串操作来选取条形码:

import urllib2
import bs4 as bs
import re
import urlparse

url = 'http://www.tesco.com/groceries/SpecialOffers/SpecialOfferDetail/Default.aspx?promoId=A31033985'

response = urllib2.urlopen(url)
content = response.read()
# with open('/tmp/test.html', 'w') as f:
#     f.write(content)
# Useful for debugging off-line:
# with open('/tmp/test.html', 'r') as f:
#     content = f.read()
soup = bs.BeautifulSoup(content)
barcodes = set()
for tag in soup.find_all('img', {'src': re.compile(r'/pi/')}):
    href = tag['src']
    scheme, netloc, path, query, fragment = urlparse.urlsplit(href)
    barcodes.add(path.split('\\')[1])

print(barcodes)

收益率

^{pr2}$

相关问题 更多 >

    热门问题