关于python的正则表达式有一些疑问

发布于 2025-01-26 22:00:55 字数 468 浏览 1 评论 0原文

好吧,我已经有这个脚本了:

#!/usr/bin/python3

import requests
from bs4 import BeautifulSoup
import re

def get_html(url):
    r = requests.get(url)
    return r.content

url = "https://foxnews.com/"
html = get_html(url)

pattern = re.compile(r'(https?\/\/).*\.(jpg|jpeg|png)')
matches = re.findall(pattern, html)

for match in matches:
    print(match)

但是,我会收到一个错误:typeError:无法在类似字节的对象上使用字符串模式,

我该如何获得此功能,以便我使用Regex从网站上刮下来的HTML找到映像链接?

Ok, I've got this script:

#!/usr/bin/python3

import requests
from bs4 import BeautifulSoup
import re

def get_html(url):
    r = requests.get(url)
    return r.content

url = "https://foxnews.com/"
html = get_html(url)

pattern = re.compile(r'(https?\/\/).*\.(jpg|jpeg|png)')
matches = re.findall(pattern, html)

for match in matches:
    print(match)

But, I get an error: TypeError: cannot use a string pattern on a bytes-like object

How can I get this so that I use regex to find image links from the HTML I scraped from websites?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

酷遇一生 2025-02-02 22:00:55

r.content返回字节中的内容,而您需要将Unicode文本在其上使用。

def get_html(url):
    r = requests.get(url)
    return r.text # instead of r.content

r.content returns the content in bytes, instead you need to get the unicode text to use regex on it.

def get_html(url):
    r = requests.get(url)
    return r.text # instead of r.content
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文