【问题标题】:Scrapy: Select specific word due to search characters in HTML TextScrapy:由于 HTML 文本中的搜索字符而选择特定单词
【发布时间】:2017-11-29 13:01:04
【问题描述】:

我有以下 HTML 脚本,我在其中搜索特定单词。

<tbody>
            <tr>
                <th>Berufsbezeichnung:</th>
                <td class="gray">ExampleName</td>
            </tr>
                        <tr>
                <th>Anrede:</th>
                <td class="gray">Herrn</td>
            </tr>
                        <tr>
                <th>Name:</th>
                <td class="gray">ExampleLastName</td>
            </tr>
                        <tr>
                <th>Vorname:</th>
                <td class="gray">ExampleSurname</td>
            </tr>
            …
</tbody>

我想要不同的变量“Berufsbezeichnung”、“Anrede”、...必须用正确的内容填充。在相同的数据集中,例如缺少“Berufsbezeichnung”,所以这个变量必须留空。

我尝试了一个搜索内容的scrapy脚本,但它不起作用:

soup = BeautifulSoup(response.css('table').extract()[0],'lxml')

for elem in soup.findAll('tr'):
    for eleme in elem.findAll('th'):
        if eleme.get_text()=='Berufsbezeichnung:':
            Berufsbezeichnung = elem.css('td.gray::text')
        if eleme.get_text()=='Anrede:':
            Anrede = elem.css('td.gray::text')
        ...

有人有想法或者更简单的方法吗?

非常感谢!

【问题讨论】:

  • 在开始时将默认值分配给Berufsbezeichnung - 它可以是空字符串(或无)。如果它没有找到它,那么你将拥有这个带有空/默认字符串的变量。
  • 你在使用scrapy吗?如果是,你真的不需要 bsoup

标签: python html beautifulsoup scrapy


【解决方案1】:

试试这个:

search_by_header = '//th[contains(., "{}")]/following-sibling::td/text()'.format
Berufsbezeichnung = response..xpath(search_by_header("Berufsbezeichnung")).extract_first()
Anrede = response.xpath(search_by_header("Anrede")).extract_first()

【讨论】:

  • 非常感谢!完美运行!
【解决方案2】:

正如@eLRuLL 评论中所指出的,我不明白你为什么使用BeautifulSoup,因为scrapy 已经有powerful tool available

对于你的情况,我建议你简单地使用xpath:

extracted_values = {} # Store the extracted values in a dictionnary

# Iterate on the tr node containted in the table node
for tr_selector in response.selector.xpath('//table//tr'):
     th_text = tr_selector.xpath('./th/text()').extract_first()

     if th_text: # The th node contain text, read the text from the td node
        extracted_values[th_text] = tr_selector.xpath('./td/text()').extract_first()

【讨论】:

  • 你好克莱门特,非常感谢!我还在努力适应scrapy和python,所以非常感谢每一个人!
猜你喜欢
  • 2017-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-18
  • 1970-01-01
  • 2018-07-17
  • 2011-09-16
相关资源
最近更新 更多