python爬虫代码范例——AI呈献
以下是一个简单的Python爬虫代码示例,用于从给定的URL爬取网页内容:
```python
import requests
from bs4 import BeautifulSoup
def get_html(url):
response = requests.get(url)
if response.status_code == 200:
return response.text
else:
return None
def get_data(html):
soup = BeautifulSoup(html, 'html.parser')
# 在这里使用BeautifulSoup选择你感兴趣的数据,例如所有的链接
links = soup.find_all('a')
for link in links:
print(link.get('href'))
def main():
url = input("请输入要爬取的网址:")
html = get_html(url)
if html is not None:
get_data(html)
else:
print("请求失败")
if __name__ == '__main__':
main()
```
这段代码使用了Python的requests库来发送HTTP请求,并使用BeautifulSoup库来解析HTML。它首先请求给定的URL,然后解析返回的HTML内容,并选择所有链接进行打印。你可以根据自己的需求修改`get_data`函数,以选择你感兴趣的数据。