Feapder: 文字列形式の HTML テキストを応答に変換します

シーンの説明

Python クローラー プロジェクトで作業する場合、文字列形式の HTML テキストを Feapder Response 形式に変換し、XPath、CSS、BeautifulSoup などを使用して必要なデータを解析する必要がある場合があります。

環境構成

  • Python 3.9.13
  • フェーダー 1.7.9

文字列の例

text = """
<tr>
    <td>2022-10-09</td>
    <td>4350.00</td>
    <td class=" rise">10.00</td>
    <td class=" rise">0.23%</td>
</tr>
<tr>
    <td>2022-10-08</td>
    <td>4340.00</td>
    <td class=" rise">30.00</td>
    <td class=" rise">0.70%</td>
</tr>
"""

実行計画

from feapder.network.selector import Selector

# 将字符串格式的HTML文本转换为Response格式
selector = Selector(text)
print(selector)
# 针对转换为Response格式的内容使用XPath解析
selector.xpath('//tr')

印刷結果:

<Selector xpath=None data='<html><body><tr>\n    <td>2022-10-09</td>\n    <td>4350.00</td>\n    <td class=" rise">10.00</td>\n    <td class=" rise">0.23%</td>\n</tr>\n<tr>\n    <td>2022-10-08</td>\n    <td>4340.00</td>\n    <td class=" rise">30.00</td>\n    <td class=" rise">0.70%</td>\n</tr></body></html>'>

完全なコード

from feapder.network.selector import Selector

text = """
<tr>
    <td>2022-10-09</td>
    <td>4350.00</td>
    <td class=" rise">10.00</td>
    <td class=" rise">0.23%</td>
</tr>
<tr>
    <td>2022-10-08</td>
    <td>4340.00</td>
    <td class=" rise">30.00</td>
    <td class=" rise">0.70%</td>
</tr>
"""

selector = Selector(text)
tr_list = selector.xpath('//tr')
thead = ['date', 'value', 'price_che_value', 'price_che_range']
result = {
    
    }
for tr in tr_list:
    for td, th in zip(tr.xpath('./td'), thead):
        result[th] = td.xpath('./text()').get()
    print('=' * 60)
    print(result)

印刷結果

============================================================
{'date': '2022-10-09', 'value': '4350.00', 'price_che_value': '10.00', 'price_che_range': '0.23%'}
============================================================
{'date': '2022-10-08', 'value': '4340.00', 'price_che_value': '30.00', 'price_che_range': '0.70%'}

おすすめ

転載: blog.csdn.net/qq_34562959/article/details/127243816