gpt4 book ai didi

python-3.x - Python 3 - 无法使用 re 库进行打印

转载 作者:行者123 更新时间:2023-12-03 11:19:20 26 4
gpt4 key购买 nike

我有这个代码:

import requests
from bs4 import BeautifulSoup
import re


url = "http://www.rockefeller.edu/research/areas/summary.php?id=1"
r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser')
for x in (soup.find_all(string=re.compile('comment'))):
print(x.parent)
print(x.parent.name)

当我听说它应该打印 <a href="/about/comments">Comments</a> 时,它什么也没打印出来和 a我正在使用:
要求:2.7.0
beautifulsoup4: 4.4.0
python :3.4.3
在 python Idle 上运行:Macbook Pro

最佳答案

re.compile() 默认区分大小写匹配。你必须设置标志 re.I使其不区分大小写。请参阅以下演示示例:

import requests
from bs4 import BeautifulSoup
import re


url = "http://www.rockefeller.edu/research/areas/summary.php?id=1"
r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser')

for x in (soup.find_all(True,text=re.compile(r'comment', re.I))):
print(x)

输出:

<a href="/about/comments">Comments</a>

关于python-3.x - Python 3 - 无法使用 re 库进行打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31757499/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com