แยก lxml xpath สำหรับตาราง html

ฉันมีเอกสาร html ที่คล้ายกับต่อไปนี้:

<html xmlns="http://www.w3.org/1999/xhtml" xmlns="http://www.w3.org/1999/xhtml">
    <div id="Symbols" class="cb">
    <table class="quotes">
    <tr><th>Code</th><th>Name</th>
        <th style="text-align:right;">High</th>
        <th style="text-align:right;">Low</th>
    </tr>
    <tr class="ro" onclick="location.href='/th/xyz.com/A.htm';" style="color:red;">
        <td><a href="/th/xyz.com/A.htm" title="Display,A">A</a></td>
        <td>A Inc.</td>
        <td align="right">45.44</td>
        <td align="right">44.26</td>
    <tr class="re" onclick="location.href='/th/xyz.com/B.htm';" style="color:red;">
        <td><a href="/th/xyz.com/B.htm" title="Display,B">B</a></td>
        <td>B Inc.</td>
        <td align="right">18.29</td>
        <td align="right">17.92</td>
</div></html>

ฉันต้องดึงข้อมูล code/name/high/low ออกจากตาราง

ฉันใช้โค้ดต่อไปนี้จากหนึ่งในตัวอย่างที่คล้ายกันใน Stack Over Flow:

#############################
import urllib2
from lxml import html, etree

webpg = urllib2.urlopen(http://www.eoddata.com/stocklist/NYSE/A.htm).read()
table = html.fromstring(webpg)

for row in table.xpath('//table[@class="quotes"]/tbody/tr'):
    for column in row.xpath('./th[position()>0]/text() | ./td[position()=1]/a/text() | ./td[position()>1]/text()'):
        print column.strip(),
    print

#############################

ฉันไม่ได้รับอะไรเลย ฉันต้องเปลี่ยน xpath วงแรกเป็น table.xpath('//tr') จาก table.xpath('//table[@class="quotes"]/tbody/tr')

ฉันแค่ไม่เข้าใจว่าทำไม xpath('//table[@class="quotes"]/tbody/tr') ถึงไม่ทำงาน


person mkt2012    schedule 07.04.2011    source แหล่งที่มา
comment
ฉันพบปัญหาของฉัน แท็ก ‹tbody› ถูกลบออกไปแล้ว จาก Firebug ‹tbody› จะแสดงต่อจาก ‹table class=quotes› และก่อนแท็ก ‹tr›   -  person mkt2012    schedule 07.04.2011
comment
ใช่ นี่คือ คำถามที่พบบ่อย: เบราว์เซอร์เพิ่มองค์ประกอบบังคับ (X)HTML (เช่น head และ tbody) ให้กับ DOM โดยวิธีนี้คือสิ่งที่ @samplebias' คำตอบพูด   -  person    schedule 08.04.2011
comment
เป็นไปได้ที่ซ้ำกันของ ปัญหา Python lxml XPath   -  person    schedule 08.04.2011


คำตอบ (1)


คุณอาจกำลังดู HTML ใน Firebug ใช่ไหม เบราว์เซอร์จะแทรกแท็กโดยนัย <tbody> เมื่อไม่มีอยู่ในเอกสาร ไลบรารี lxml จะประมวลผลเฉพาะแท็กที่อยู่ในสตริง HTML แบบดิบเท่านั้น

ละเว้นระดับ tbody ใน XPath ของคุณ ตัวอย่างเช่น วิธีนี้ได้ผล:

tree = lxml.html.fromstring(raw_html)
tree.xpath('//table[@class="quotes"]/tr')
[<Element tr at 1014206d0>, <Element tr at 101420738>, <Element tr at 1014207a0>]
person samplebias    schedule 07.04.2011
comment
ฉันประสบปัญหานี้กับ Chrome เช่นกัน กำลังใช้คุณสมบัติ Copy XPath ในเมนูคลิกขวา 'ตรวจสอบ' ค่อนข้างโง่ - person ficuscr; 24.02.2014
comment
คุณรู้จักกฎการเปลี่ยนเส้นทางอื่นๆ ที่สามารถเกิดขึ้นได้ใน FF/Chrome หรือไม่ มันจะน่าสนใจที่จะรวบรวมพวกมัน - person lajarre; 21.08.2015