[英]How can i use lxml xpath to get specific element from web scraping data
I followed the link below to scrape historical data from Prize Zombie: 我点击了以下链接,从“僵尸奖”中抓取了历史数据:
https://impythonist.wordpress.com/2015/01/06/ultimate-guide-for-scraping-javascript-rendered-web-pages/
https://impythonist.wordpress.com/2015/01/06/ultimate-guide-for-scraping-javascript-rendered-web-pages/
The script I have is like below: 我的脚本如下所示:
import requests
import pandas as pd
import sys
import csv
import urllib2
import sys
import time
from bs4 import BeautifulSoup
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.QtWebKit import *
from lxml import html
class Render(QWebPage):
def __init__(self, url):
self.app = QApplication(sys.argv)
QWebPage.__init__(self)
self.loadFinished.connect(self._loadFinished)
self.mainFrame().load(QUrl(url))
self.app.exec_()
def _loadFinished(self, result):
self.frame = self.mainFrame()
self.app.quit()
url = 'https://www.pricezombie.com/viewproduct/pF/5jNvj/Align-Probiotic-Supplement-42-count'
r = Render(url)
result = r.frame.toHtml()
formatted_result = str(result.toAscii())
tree = html.fromstring(formatted_result)
According the author, now I need to use xpath to get the element I want. 根据作者的说法,现在我需要使用xpath来获取所需的元素。
However, I really can't figure out how to get those specific elements from the tree. 但是,我真的不知道如何从树中获取这些特定元素。
The html part should look like this: html部分应如下所示:
class="pt1">$27.51, May 15 - Jun 10
And the information I need is: 我需要的信息是:
<g class="pzmo">
<rect x="91" y="14" height="216" width="7" style="fill:#ccc" fill-opacity="0.2"></rect>
<rect fill-opacity="0.9" class="prec" x="98" y="14" width="170" height="20"></rect>
<text x="103" y="28" class="pt1">$27.51, May 15 - Jun 10</text>
</g>
Could anyone tell me what's the xpath for that? 谁能告诉我这个的xpath是什么?
The xpath is, for example: xpath例如:
//*[@id="chart3Dqt"]/svg/g[412]/text[1]
If you want to vary the index you can substitute with a formatting field: 如果要更改索引,可以用格式字段代替:
>>> xpath = '//*[@id="chart3Dqt"]/svg/g[{index}]/text[1]'
>>> xpath.format(index=412)
//*[@id="chart3Dqt"]/svg/g[412]/text[1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.