不使用BeautifulSoup应该怎么做
时间: 2024-02-05 20:05:25 浏览: 38
如果你不想使用 BeautifulSoup 库来解析网页,你可以使用其他方法来实现爬取网页中的图片。一种常见的方法是使用正则表达式来提取图片的 URL。
以下是一个示例代码,展示如何使用正则表达式来提取图片 URL:
```python
import re
import requests
def crawl_images(url, num_images):
response = requests.get(url)
html_content = response.text
pattern = r'<img.*?src="(.*?)".*?>'
image_urls = re.findall(pattern, html_content)
count = 0
for image_url in image_urls:
if count == num_images:
break
if image_url.startswith('http'):
response = requests.get(image_url)
with open(f'image_{count}.jpg', 'wb') as f:
f.write(response.content)
count += 1
crawl_images('https://example.com', 100)
```
上述代码与之前的示例类似,只是使用了正则表达式来提取图片的 URL。正则表达式 `r'<img.*?src="(.*?)".*?>'` 匹配了 `<img>` 标签中的 `src` 属性,并提取出图片的 URL。
需要注意的是,正则表达式可能在某些情况下并不准确或适用于所有网页。使用 BeautifulSoup 库通常更可靠和灵活,因为它可以处理复杂的 HTML 结构。但如果你坚决不使用 BeautifulSoup,使用正则表达式也是一种可行的方法。