可以使用 Python 的第三方库 requests
和 BeautifulSoup
来编写一个爬虫。
首先,需要安装这两个库,可以使用 pip
命令来安装:
pipinstall requests
pip install beautifulsoup4
然后,可以使用 requests
库来发送 HTTP 请求,获取网页内容。例如:
import requests
url = 'http://example.com'
response = requests.get(url)
html = response.text
接着,可以使用 BeautifulSoup
库来解析 HTML 文本,提取你感兴趣的信息。例如:
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'html.parser')
# 提取所有的链接
links = soup.find_all('a')
for link in links:
print(link.get('href'))
完整的爬虫代码可能长这样:
import requests
from bs4 import BeautifulSoup
def crawl(url):
# 发送 HTTP 请求,获取响应内容
response = requests.get(url)
html = response.text
# 解析 HTML,提取信息
soup = BeautifulSoup(html, 'html.parser')
links = soup.find_all('a')
# 处理每个链接
for link in links:
href = link.get('href')
# 对链接进行处理,提取有效信息
print(href)
if __name__ == '__main__':
crawl('http://example.com')
注意:在编写爬虫时,要遵守网站的 robots.txt 文件,不要对网站进行滥用或者恶意攻击。