【问题标题】:Python 3 - Can't print using the re libraryPython 3 - 无法使用 re 库打印
【发布时间】:2015-08-01 02:06:43
【问题描述】:

我有这个代码:

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
美丽的汤4:4.4.0
Python : 3.4.3
在 python Idle 上运行:Macbook Pro

【问题讨论】:

    标签: python-3.x beautifulsoup python-requests


    【解决方案1】:

    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>
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多