【问题标题】:Webscraping multiline cells in tables using CSS Selectors and Python使用 CSS 选择器和 Python 抓取表格中的多行单元格
【发布时间】:2017-01-01 03:18:54
【问题描述】:

所以我正在抓取一个页面 (http://canoeracing.org.uk/marathon/results/burton2016.htm),其中表格中有多行单元格:

我正在使用以下代码来抓取每一列(下面的代码恰好抓取了名称):

import lxml.html
from lxml.cssselect import CSSSelector

# get some html
import requests

r = requests.get('http://canoeracing.org.uk/marathon/results/burton2016.htm')
# build the DOM Tree
tree = lxml.html.fromstring(r.text)
# construct a CSS Selector
sel1 = CSSSelector('body > table > tr > td:nth-child(2)')
# Apply the selector to the DOM tree.
results1 = sel1(tree)
# get the text out of all the results
data1 = [result.text for result in results1]

不幸的是,它只返回每个单元格的名字,而不是两者。我在 webscraping tool Kimono 上尝试了类似的东西,我可以同时抓取两者,但是我想发送一个 Python 代码,因为 Kimono 在运行多个网页时会掉下来。

【问题讨论】:

  • 您不需要使用CSSSelector,您可以按照我对您上一个问题的回答拨打tree.cssselect

标签: python css web-scraping


【解决方案1】:

问题是某些单元格包含多个由<br> 分隔的文本节点。在这种情况下,找到所有文本节点并加入它们:

data1 = [", ".join(result.xpath("text()")) for result in rows] 

对于屏幕截图中提供的行,您将获得:

OSCAR HUISSOON, FREJA WEBBER
ELLIE LAWLEY, RHYS TIPPINGS
ALLISON MILES, ALEX MILES
NICOLA RUDGE, DEBORAH CRUMP

您也可以使用.text_content() 方法,但您会丢失文本节点之间的分隔符,结果中会出现OSCAR HUISSOONFREJA WEBBER 之类的内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-31
    • 1970-01-01
    • 2013-02-20
    • 1970-01-01
    • 2014-07-17
    • 2021-06-28
    • 2020-09-10
    相关资源
    最近更新 更多