用python写爬虫

首先,需要导入这两个库:

 
 

import requests
from bs4 import BeautifulSoup

然后,确定要爬取的网站的URL,并使用requests.get()方法发送请求:

 
 

url = "https://www.example.com"
response = requests.get(url)

接下来,可以通过response.content属性获取响应内容,并使用BeautifulSoup库将其解析为HTML:

 
 

python复制插入

soup = BeautifulSoup(response.content, 'html.parser')

现在,可以使用BeautifulSoup提供的方法从HTML中获取所需的数据。例如,可以使用find_all()方法查找所有的链接:

 
 

links = soup.find_all('a')
for link in links:
    print(link.get('href'))

此外,还可以使用find()方法查找单个元素,以及使用CSS选择器语法查找元素。更多关于BeautifulSoup库的用法,请参考官方文档。

最后,别忘了添加异常处理以应对可能出现的网络错误:

 
 

try:
    response = requests.get(url)
    soup = BeautifulSoup(response.content, 'html.parser')
    # 其他操作
except requests.exceptions.RequestException as e:
    print(e)

完整代码示例:

 
 

import requests
from bs4 import BeautifulSoup

url = "https://www.example.com"

try:
    response = requests.get(url)
    soup = BeautifulSoup(response.content, 'html.parser')
    links = soup.find_all('a')
    for link in links:
        print(link.get('href'))
except requests.exceptions.RequestException as e:
    print(e)

复制插入

猜你喜欢

转载自blog.csdn.net/yydsdeni/article/details/132548963