举一个爬虫的python代码的例子
时间: 2024-05-09 19:17:41 浏览: 6
当然可以,这是一个简单的爬虫代码:
```python
import requests
from bs4 import BeautifulSoup
# 定义要爬取的网页链接
url = 'https://www.example.com/'
# 发送请求,获取HTML页面
response = requests.get(url)
html_doc = response.text
# 解析HTML页面
soup = BeautifulSoup(html_doc, 'html.parser')
# 找到想要的元素,如网页标题
title = soup.title.string
# 输出结果
print(title)
```
这个代码使用 Python 的 requests 库发送请求,通过 BeautifulSoup 库对 HTML 页面进行解析和处理,最后找到页面中的标题并输出。
相关问题
用Python写一个爬虫图片代码
以下是一个简单的爬虫图片代码示例,使用Python的requests和BeautifulSoup库:
```python
import requests
from bs4 import BeautifulSoup
url = "https://www.example.com/images"
response = requests.get(url)
soup = BeautifulSoup(response.content, "html.parser")
images = soup.find_all("img")
for image in images:
image_url = image["src"]
image_response = requests.get(image_url)
with open(image_url.split("/")[-1], "wb") as f:
f.write(image_response.content)
```
该代码首先使用requests库获取目标网页的HTML内容,然后使用BeautifulSoup库解析HTML,找到所有的图片标签,并提取每个图片的URL。接下来,使用requests库再次获取每个图片的内容,并将其保存到本地。在这个例子中,图片被保存到与其URL相同的文件名中。
python写一个爬虫代码
好的,下面是一个简单的爬虫代码的例子:
```
import requests
from bs4 import BeautifulSoup
def get_html(url):
"""
获取网页的html内容
"""
try:
r = requests.get(url)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return "产生异常"
def get_content(html):
"""
解析html,获取网页中的数据
"""
soup = BeautifulSoup(html, 'html.parser')
# 这里使用了css选择器, 根据自己的需求选择合适的方法解析网页
items = soup.select('body > div > div > div.col-md-9 > div > div > div > div.caption > h4 > a')
# 初始化一个列表,用来存储解析后的数据
news = []
for item in items:
news.append({'title': item.get_text(), 'link': item.get('href')})
return news
def spider():
"""
爬虫的主函数
"""
url = "http://www.santostang.com/"
html = get_html(url)
content = get_content(html)
print(content)
if __name__ == "__main__":
spider()
```
这个爬虫的目标是爬取这个网站(http://www.santostang.com/)的新闻标题和链接。
希望这个例子能帮到你!