我正在开发一个程序,它可以解析网站上的不同配置文件。所有的配置文件都有一些文本,为了获取这些字段,我使用.index()对象对它们进行切片。然而,这些概要文件的所有者在极少数情况下可能会在其“概要文件描述”中使用实际html文档中的一些关键字。概要文件描述的文本是html文档的前几行之一。如何确保每次解析文档时都跳过前几行?在
示例代码:
from bs4 import BeatifulSoup
import urllib.request
country_id = 56451
country_url = "http://www.blocgame.com/stats.php?id=" + str(country_id)
country_source = urllib.request.urlopen(country_url)
country_page = BeautifulSoup(country_source, 'html.parser')
country_text = country_page.get_text()
#This is a game where each player owns their country in the cold war
#This checks for the airforce level
def check_airfoce_cosmetic():
cforce_slice1 = int(country_text.index("Airforce:"))
cforce_slice2 = int(country_text.index("Navy:"))
country_airforce_cosmetic = country_text[cforce_slice1:cforce_slice2]
print(country_airforce_cosmetic + "\n\n")
#However, the player might have something in their description bragging about their airforce.
如果这个问题的措辞对你不好,就告诉我。在
通过使用bs4的decompose删除HTML中潜在的危险部分,我已经解决了这样一个问题。例如,对于如下所示的page_html soup:
<about>Not important, and possibly dangerous!</about> <stats>This is the important part.</stats>
我会做一些类似的事情:
not_needed = page_html.about not_needed.decompose()
你只剩下
<stats>This is the important part.</stats>
。因此,您可以完全删除用户的个人描述,然后安全地提取您需要的任何内容。在如果不想使用索引,可以将文本作为字符串拉出,然后解析该字符串。不是最优雅,但很管用。在
生产
^{pr2}$相关问题 更多 >
编程相关推荐