如何使用lxml(或BeautifulSoup)提取两个跨度之间的文本?
How to extract the text between two spans with lxml (or BeautifulSoup)?
给定 this 页面,我想找出样式 ID 的值:
我使用浏览器的开发人员工具获得 唯一选择器:
li.attribute-list-item:nth-child(1) > span:nth-child(1)
那么 urllib2
和 lxml
的 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) 的单个元素的文本值:
它给我的是文本 'Style ID' 而不是它后面的实际值。外观如下:
如何获取号码(在本例中为 555088 117)?我也欢迎基于 BeautifulSoup
的建议。
编辑: 我特别寻求基于 CSS(class 名称或选择器)的方法。
与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()
给定 this 页面,我想找出样式 ID 的值:
我使用浏览器的开发人员工具获得 唯一选择器:
li.attribute-list-item:nth-child(1) > span:nth-child(1)
那么 urllib2
和 lxml
的 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) 的单个元素的文本值:
它给我的是文本 'Style ID' 而不是它后面的实际值。外观如下:
如何获取号码(在本例中为 555088 117)?我也欢迎基于 BeautifulSoup
的建议。
编辑: 我特别寻求基于 CSS(class 名称或选择器)的方法。
与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()