【问题标题】:How send value from ini file to bs4 find? (python)如何将值从ini文件发送到bs4 find? (Python)
【发布时间】:2021-12-30 14:32:53
【问题描述】:

如何将值从 ini 文件发送到 BeautifulSoup.find()?

settings.ini:

   [tpk]
      pattern = 'h2'

main.py:

   import configparser
   config = configparser.ConfigParser()
   config.read('settings.ini')
   ...
   result = soup.find(config['tpk']['pattern']).text
   print(result)

此解决方案不起作用.. 谢谢你,对不起我的英语

【问题讨论】:

  • 你有没有试过先打印config['tpk']['pattern'],看看是不是应该的?
  • 你确定你的汤里有h2吗?

标签: python python-3.x beautifulsoup configparser


【解决方案1】:

所以基本上问题出在您的 settings.ini 中。您不能将 h2 存储为“h2”,因为当您尝试将其导入 python 代码时,它会被导入为网站上不存在的“'h2'”。 您需要将其存储为:

[tpk]
pattern = h2

示例代码

import requests
import configparser
from bs4 import BeautifulSoup

URL = "http://www.techonthenet.com/html/elements/h2_tag.php"
page = requests.get(URL)

config = configparser.ConfigParser()
config.read("settings.ini")
pattern = config.get("tpk", "pattern")

soup = BeautifulSoup(page.content, "html.parser")
results = soup.find(pattern)

print(results.prettify())

你可以自己测试一下。

【讨论】:

    猜你喜欢
    • 2022-01-21
    • 2021-12-27
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 2021-04-27
    • 2019-10-22
    • 2020-09-20
    • 1970-01-01
    相关资源
    最近更新 更多