gpt4 book ai didi

python - 使用 Xpath、Python 从网站提取信息

转载 作者:太空宇宙 更新时间:2023-11-03 17:47:16 24 4
gpt4 key购买 nike

尝试从网站中提取一些有用的信息。我现在有点卡住了,需要你的帮助!

我需要此表中的信息

http://gbgfotboll.se/serier/?scr=scorers&ftid=57700

我编写了这段代码,并得到了我想要的信息:

import lxml.html
from lxml.etree import XPath

url = ("http://gbgfotboll.se/serier/?scr=scorers&ftid=57700")

rows_xpath = XPath("//*[@id='content-primary']/div[1]/table/tbody/tr")
name_xpath = XPath("td[1]//text()")
team_xpath = XPath("td[2]//text()")

league_xpath = XPath("//*[@id='content-primary']/h1//text()")


html = lxml.html.parse(url)

divName = league_xpath(html)[0]

for id,row in enumerate(rows_xpath(html)):
scorername = name_xpath(row)[0]
team = team_xpath(row)[0]
print scorername, team


print divName

我收到此错误

    scorername = name_xpath(row)[0]
IndexError: list index out of range

我确实明白为什么会收到错误。我真正需要帮助的是我只需要前 12 行。这是提取在这三种可能的情况下应该执行的操作:

如果少于 12 行:获取除最后一行之外的所有行。

如果有12行:同上..

如果超过 12 行:只需取前 12 行。

我怎样才能做到这一点?

编辑1

它不是重复的。当然是同一个网站。但我已经完成了那个人想要的事情,即从行中获取所有值。我已经可以做到了。我不需要最后一行,并且我不希望它提取超过 12 行(如果有)..

最佳答案

我想这就是你想要的:

#coding: utf-8
from lxml import etree
import lxml.html

collected = [] #list-tuple of [(col1, col2...), (col1, col2...)]
dom = lxml.html.parse("http://gbgfotboll.se/serier/?scr=scorers&ftid=57700")
#all table rows
xpatheval = etree.XPathDocumentEvaluator(dom)
rows = xpatheval('//div[@id="content-primary"]/div/table[1]/tbody/tr')
# If there are less than 12 rows (or <=12): Take all the rows except the last.
if len(rows) <= 12:
rows.pop()
else:
# If there are more than 12 rows: Simply take the first 12 rows.
rows = rows[0:12]

for row in rows:
# all columns of current table row (Spelare, Lag, Mal, straffmal)
columns = row.findall("td")
# pick textual data from each <td>
collected.append([column.text for column in columns])

for i in collected: print i

输出:

enter image description here

关于python - 使用 Xpath、Python 从网站提取信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29595105/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com