在XPath(lxml)中管理引号 [英] Manage quotation marks in XPath (lxml)

查看:79
本文介绍了在XPath(lxml)中管理引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从给定网站的制造概览"表中提取Web元素.但是该行的名称带有'(单引号).这干扰了我的语法.我该如何克服这个问题?该代码适用于其他行.

I want to extract web elements from the table 'MANUFACTURING AT A GLANCE' in the given website. But the name of the row has ' (single quote). This is interfering with my syntax. How do I overcome this issue? This code works for other rows.

import requests
from lxml import html, etree

ism_pmi_url = 'https://www.instituteforsupplymanagement.org/ismreport/mfgrob.cfm?SSO=1'
page = requests.get(ism_pmi_url)
tree = html.fromstring(page.content)

PMI_CustomerInventories = tree.xpath('//strong[text()="Customers' Inventories"]/../../following-sibling::td/p/text()')
PMI_CustomerInventories_Curr_Val = PMI_CustomerInventories[0]

推荐答案

这是我避免出现问题的方法. 也许这并不是您真正需要的,但是可以帮助您理解这个想法.

this is my approach to avoid your problem. maybe is not what you really need, but could help to you to get the idea.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import lxml.html
import re
import requests
import lxml.html
from pprint import pprint

def load_lxml(response):
    return lxml.html.fromstring(response.text)

url = 'https://www.instituteforsupplymanagement.org/ismreport/mfgrob.cfm?SSO=1'
response = requests.get(url)
root = load_lxml(response)

headers = []
data = []
for index,row in enumerate(root.xpath('//*[@id="home_feature_container"]/div/div/div/span/table[2]/tbody/tr')):
    rows = []
    for cindex,column in enumerate(row.xpath('./th//text() | ./td//text()')):
        if cindex == 1:
            continue
        column = column.strip()
        if index == 0 or not column:
            continue
        elif index == 1:
            headers.append(column)
        else:
            rows.append(column)

    if rows and len(rows) == 6:
        data.append(rows)


data.insert(0,headers)

pprint(data)    

结果:

[['Series Index',
  'Feb',
  'Series Index',
  'Jan',
  'Percentage',
  'Point',
  'Change',
  'Direction',
  'Rate of Change',
  'Trend* (Months)'],
 ['65.1', '60.4', '+4.7', 'Growing', 'Faster', '6'],
 ['62.9', '61.4', '+1.5', 'Growing', 'Faster', '6'],
 ['54.2', '56.1', '-1.9', 'Growing', 'Slower', '5'],
 ['54.8', '53.6', '+1.2', 'Slowing', 'Faster', '10'],
 ['51.5', '48.5', '+3.0', 'Growing', 'From Contracting', '1'],
 ['47.5', '48.5', '-1.0', 'Too Low', 'Faster', '5'],
 ['68.0', '69.0', '-1.0', 'Increasing', 'Slower', '12'],
 ['57.0', '49.5', '+7.5', 'Growing', 'From Contracting', '1'],
 ['55.0', '54.5', '+0.5', 'Growing', 'Faster', '12'],
 ['54.0', '50.0', '+4.0', 'Growing', 'From Unchanged', '1']]
[Finished in 2.9s]

这篇关于在XPath(lxml)中管理引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆