帮我写一份爬虫代码把这个网站的内容爬取一下,https://www.163.com/
时间: 2023-08-11 21:04:16 浏览: 41
好的,以下是一个简单的Python爬虫代码,可以爬取网易首页的部分内容:
```python
import requests
from bs4 import BeautifulSoup
url = "https://www.163.com/"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
# 获取所有a标签的href属性和文本内容
for link in soup.find_all('a'):
href = link.get('href')
title = link.text
print(href, title)
# 获取所有img标签的src属性和alt属性
for img in soup.find_all('img'):
src = img.get('src')
alt = img.get('alt')
print(src, alt)
```
这个代码使用了requests库和BeautifulSoup库来获取网页内容和解析HTML代码。通过循环遍历a标签和img标签,分别获取它们的href、文本内容、src和alt属性,并打印输出。你可以根据自己的需求对这个代码进行修改和扩展。注意爬虫要遵守网站的爬虫规则,不要进行过度频繁的访问,以免给网站带来负担。
相关问题
python,写个爬虫代码爬取https://www.liaoxuefeng.com/wiki/1016959663602400
好的,我可以给你提供一个简单的爬虫代码,使用Python的requests和BeautifulSoup库:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://www.liaoxuefeng.com/wiki/1016959663602400'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
content = soup.select_one('.x-wiki-content')
print(content.text)
```
这个代码使用requests库获取页面内容,然后用BeautifulSoup库解析HTML,最后选择页面中的内容。你可以把最后一行print语句替换成你想要的其他操作,比如把内容写入文件等。需要注意的是,爬取网站内容时需要遵守网站的robots.txt协议,避免对网站造成不良影响。
帮我写一个爬取https://www.luogu.com.cn/contest/68651#scoreboard的代码
好的,以下是爬取https://www.luogu.com.cn/contest/68651#scoreboard的Python代码:
```python
import requests
from bs4 import BeautifulSoup
import pandas as pd
# 构造请求头
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
# 发送请求
url = 'https://www.luogu.com.cn/contest/68651#scoreboard'
response = requests.get(url, headers=headers)
# 解析网页
soup = BeautifulSoup(response.text, 'html.parser')
# 获取数据
table = soup.find("table", {"class": "lg-table"})
thead = table.find("thead")
th_list = thead.find_all("th")
columns = [th.text.strip() for th in th_list]
tbody = table.find("tbody")
tr_list = tbody.find_all("tr")
data = []
for tr in tr_list:
td_list = tr.find_all("td")
row_data = [td.text.strip() for td in td_list]
data.append(row_data)
# 保存数据到CSV文件
df = pd.DataFrame(data, columns=columns)
df.to_csv("contest_data.csv", index=False)
```
这段代码会使用requests库向指定URL发送请求,并使用BeautifulSoup库解析返回的HTML代码。我们可以从HTML代码中找到比赛排名表格的相关信息,并使用pandas库将表格数据保存到CSV文件中。
请注意,这段代码中使用了一个User-Agent请求头,这是为了模拟浏览器发送的请求,避免被网站识别为爬虫并屏蔽。如果您需要爬取其他网站,请根据需要修改请求头。