【问题标题】:How can I create a CSS Selector to select the content of a td using the content of a th?如何创建 CSS 选择器以使用 th 的内容选择 td 的内容?
【发布时间】:2019-01-09 12:45:09
【问题描述】:

我正在使用 scrapy 编写爬虫,并通过使用以下 python 行,我设法获取了我正在寻找的数据:

Python 行:

response.css("article.college div.span8.profile > table > tbody > tr").extract()

它返回以下结果:

['<tr>\n<th>Institution Name:</th>\n<td>Harvard University</td>\n</tr>',
 '<tr>\n<th>Administration</th>\n<td>Private</td>\n</tr>',
 '<tr>\n<th>State</th>\n<td>\nMassachussets\t\n</td>\n</tr>']

但是,我想访问按属性名称索引的属性值。我想做这样的事情:

response.css(<magic containing 'Institution Name'>)

并且能够检索到对应的值,在本例中是这样的:

\n<td>Harvard University</td>\n

有人可以帮我解决这个问题吗?

谢谢

【问题讨论】:

    标签: css web-scraping scrapy css-selectors


    【解决方案1】:

    您可以尝试使用 XPath:

    response.xpath('//tr[th="Institution Name:"]/td/text()').extract()
    

    【讨论】:

      【解决方案2】:

      在这种情况下,我使用像这样的列表推导

      institution_name = [line.css("td").extract_first() for line in response.css("article.college div.span8.profile > table > tbody > tr") if "Institution Name" in line.extract()]
      

      【讨论】:

        【解决方案3】:

        我正在将您的提取器修改为 xpath :

        response.xpath("//table//tbody//tr[contains(., 'Institution Name')]/td/text()").extract()
        

        我刚刚添加了任何包含Institution Name 文本(区分大小写)的tr,然后从tr 中选择td

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-07-09
          • 2013-11-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多