【问题标题】:How to extract the text between two spans with lxml (or BeautifulSoup)?如何使用lxml(或BeautifulSoup)提取两个跨度之间的文本?
【发布时间】:2016-02-07 00:17:00
【问题描述】:

鉴于 this 页面,我正在寻找样式 ID 的值:

我使用浏览器的开发工具获得了唯一选择器

li.attribute-list-item:nth-child(1) > span:nth-child(1)

那么使用 urllib2lxml 的 CSS 功能:

import urllib2
from lxml import etree 
from lxml.cssselect import CSSSelector    
req = urllib2.Request(url, headers={'User-Agent' : "Magic Browser"}) 
con = urllib2.urlopen( req )
htmlparser = etree.HTMLParser()
tree = etree.parse(con, htmlparser)
x = CSSSelector('li.attribute-list-item:nth-child(1) > span:nth-child(1)')

如果我再得到 x(tree) 的单个元素的文本值:

它给了我文本“样式 ID”,而不是它后面的实际值。下面是它的外观:

如何获取号码(在本例中为 555088 117)?我也欢迎基于BeautifulSoup 的建议。

编辑:我专门寻找基于 CSS(类名或选择器)的方法。

【问题讨论】:

  • 如果我在 Firebug 或开发者工具中突出显示数字本身,请不要给我任何方法来识别它(通过 CSS、XPath 或其他方式)

标签: python html css beautifulsoup lxml


【解决方案1】:

requests + lxml

import requests
from lxml import html

response = requests.get("http://www.flightclub.com/air-jordan-1-retro-high-og-unc-white-dk-powder-blue-012304")
tree = html.fromstring(response.content)

style_id = tree.xpath('//ul[@class="mb-padding product-attribute-list"]/li[@class="attribute-list-item"][1]/text()[2]')[0].replace(',','').strip()
print style_id

输出:

555088 117

注意:

为避免IndexError: list index out of range万一网站结构发生变化,您可以替换:

style_id = tree.xpath('//ul[@class="mb-padding product-attribute-list"]/li[1]/text()[2]')[0].replace(',','').strip()

与:

style_id = ''.join(tree.xpath('//ul[@class="mb-padding product-attribute-list"]/li[1]/text()[2]')).replace(',','').strip()

【讨论】:

  • 谢谢。因为有问题的元素包含多个部分、换行符、空格等(正如您所发现的),这就是为什么我正在寻求一种更强大的基于 CSS 选择器的方法。
  • 我的荣幸。我认为这是最准确的方法,因为全文是在一起的,没有被任何节点分割。我已将 li[1] 更新为 li[@class="attribute-list-item"][1] 以更具体。
猜你喜欢
  • 2016-06-22
  • 2019-03-09
  • 2021-10-05
  • 1970-01-01
  • 1970-01-01
  • 2019-09-10
  • 1970-01-01
  • 2011-10-18
  • 2016-03-27
相关资源
最近更新 更多