写一个简单的python爬虫
时间: 2023-07-23 18:55:08 浏览: 46
好的,下面是一个简单的 Python 爬虫的示例代码:
```python
import requests
from bs4 import BeautifulSoup
# 发送GET请求获取页面内容
url = 'https://www.example.com'
response = requests.get(url)
# 用BeautifulSoup解析页面内容
soup = BeautifulSoup(response.text, 'html.parser')
# 找到页面中的所有链接
links = soup.find_all('a')
# 输出链接的文本和URL
for link in links:
text = link.text.strip()
url = link['href']
print(text, url)
```
这个爬虫使用 requests 库发送 GET 请求获取页面内容,然后使用 BeautifulSoup 库解析页面内容,找到页面中的所有链接,最后输出链接的文本和 URL。请注意,这只是一个简单的示例,实际的爬虫可能需要更复杂的逻辑和处理。同时,请注意不要滥用爬虫,尊重网站的 robots.txt 文件和使用合适的爬虫频率。
相关问题
写一个简单的Python爬虫代码
当然可以,以下是一个简单的 Python 爬虫代码,可以爬取指定网站的页面内容并保存到本地。
```python
import requests
url = "https://www.example.com"
response = requests.get(url)
if response.status_code == 200:
with open("example.html", "w") as f:
f.write(response.text)
else:
print("Failed to get the page content.")
```
这个爬虫代码使用了 requests 库来发送 HTTP GET 请求,并检查 HTTP 响应状态码来判断是否成功获取页面内容。如果获取成功,就将页面内容保存到一个名为 example.html 的本地文件中。
写一个用python爬虫的代码
以下是一个使用Python爬虫库`requests`和`BeautifulSoup`来爬取网页的示例代码:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://www.example.com'
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
# 打印网页标题
print(soup.title.text)
# 打印网页所有链接
for link in soup.find_all('a'):
print(link.get('href'))
```
该代码首先使用`requests`库获取指定网页的HTML内容,然后使用`BeautifulSoup`库来解析HTML内容。在这个示例中,我们打印了网页的标题并列出了所有链接。你可以根据需要修改和扩展该代码,以满足你自己的爬虫需求。