简单python爬虫完整代码
当涉及网络爬虫时,需要注意遵守网站的使用政策,并确保你的爬虫代码合法、合规。
pythonimport requests
from bs4 import BeautifulSoup
# 定义要爬取的目标网址
url = 'https://example.com'
# 发送 HTTP 请求
response = requests.get(url)
# 检查请求是否成功
if response.status_code == 200:
# 使用 BeautifulSoup 解析网页内容
soup = BeautifulSoup(response.text, 'html.parser')
# 通过选择器选择想要的元素,这里以 CSS 类名为例
desired_elements = soup.select('.example-class')
# 遍历选中的元素并输出
for element in desired_elements:
print(element.text)
else:
print(f'Error: {response.status_code}')
在这个例子中,你需要安装 requests 和 beautifulsoup4 这两个库。可以使用
bashpip install requests pip install beautifulsoup4
当涉及到爬虫时,首先要确保你了解并遵守网站的使用条款和法律法规。使用爬虫进行数据获取可能会违反某些网站的规定,因此请确保你有权进行爬取操作。
pythonimport requests
from bs4 import BeautifulSoup
def simple_web_scraper(url):
# 发送HTTP请求获取页面内容
response = requests.get(url)
# 检查请求是否成功
if response.status_code == 200:
# 使用BeautifulSoup解析页面内容
soup = BeautifulSoup(response.text, 'html.parser')
# 提取标题和链接
titles = soup.find_all('h2') # 假设标题使用h2标签
links = soup.find_all('a') # 假设链接使用a标签
# 打印标题和链接
for title in titles:
print("标题:", title.text.strip())
for link in links:
print("链接:", link.get('href'))
else:
print("请求失败,状态码:", response.status_code)
# 调用爬虫函数
url_to_scrape = 'https://example.com' # 替换为你要爬取的网址
simple_web_scraper(url_to_scrape)
请确保在运行爬虫之前安装了requests和beautifulsoup4库,可以使用
bashpip install requests pip install beautifulsoup4