用python写一个简单爬虫程序
时间: 2023-03-06 17:17:23 浏览: 91
可以这样写:
from urllib.request import urlopen
from bs4 import BeautifulSoup
url = 'http://example.com'
html = urlopen(url)
soup = BeautifulSoup(html, 'html.parser')
for link in soup.find_all('a'):
print(link.get('href'))
相关问题
能使用python写一个简单到爬虫程序吗
当然可以!下面是一个简单的爬虫程序,可以爬取指定网站的标题和链接:
```python
import requests
from bs4 import BeautifulSoup
url = "https://www.example.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
for link in soup.find_all("a"):
print(link.get("href"), link.text)
```
这个程序使用了 requests 库来获取网页内容,使用了 BeautifulSoup 库来解析 HTML。然后,我们可以使用 find_all() 方法来查找网页中的所有链接,然后打印出链接的地址和文本。当然,这只是一个简单的示例,实际上爬虫程序通常需要更加复杂的逻辑和处理。
使用Python写一个爬虫程序
好的,以下是一个简单的Python爬虫程序,用于爬取网页内容:
```python
import requests
url = "https://www.example.com" # 要爬取的网页地址
response = requests.get(url) # 发送请求并获取响应对象
if response.status_code == 200: # 判断响应状态码是否为200(成功)
content = response.content # 获取响应内容
# 在这里可以对响应内容进行处理,比如解析HTML等
else:
print("请求失败,状态码为:", response.status_code)
```
上面的程序使用了`requests`库来发送HTTP请求并获取响应对象,然后判断响应状态码是否为200,如果是,则获取响应内容并进行处理。在这里,我们只是简单地将响应内容打印出来了。
需要注意的是,爬虫程序需要遵守网站的规则,不要频繁地发起请求,否则可能会被封IP或者被网站封禁。此外,一些网站可能会对爬虫程序进行限制,比如使用验证码等。因此,在编写爬虫程序时,需要注意这些问题。