我正在使用 BeautifulSoup 编写一个 Web 解析器。我创建了一个使用 bs.findAll(text=True) 生成的行列表,然后逐行分割并在那里应用我的逻辑。 html_payload
是任意网页。
到目前为止,我得到的代码可以工作,但它不是很漂亮,并且让我认为必须有一种更好、更优雅的编写方式。
data_to_parse = BeautifulSoup(html_payload)
lines_to_parse = []
d = data_to_parse.findAll(text=True)
for line in d:
for line2 in line.strip().split('\n'):
if line2:
lines_to_parse.append(line2)
for line in lines_to_parse:
pass # here's where I start analyzing results
有没有人可以提出更好的方法来解决这个问题?
最佳答案
就get all the text at once并将其分成几行:
data_to_parse = BeautifulSoup(html_payload)
for line in data_to_parse.get_text().split("\n"):
pass # ... do something
关于python - 从 BeautifulSoup.findAll 创建行列表的更优雅的方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18412601/