python 爬虫 beautifulsoup example 例子

本文介绍如何使用Python的BeautifulSoup库爬取网站排行的相关数据,包括URL、Alexa排名、百度权重、PR等信息。通过遍历网页内容,解析并提取所需的数据,并将其存储到CSV文件中。

今天第一次用python的beautifulsoup,虽然比较生疏,但还是爬下来了。

爬的网站是: 网站排行

爬取的内容:包括网站的url, aleax排名,百度权重, PR等

import urllib2
import pandas as pd
from bs4 import BeautifulSoup

def urlprocess(url):
    u = url.replace('/Html/site_','').replace('.html','').replace('/site_www.','www.')
    return u

def baiduprs(baidu):
    return baidu.replace('/themes/default/images/baidu/','').replace('.gif','')

def PRprs(pr):
    return pr.replace('/themes/default/images/ranks/Rank_','').replace('.gif','')

url = 'http://top.chinaz.com/all/index_alexa.html'
res = pd.DataFrame(columns=['host','alex','baidu','pr','Inverse chain number','score','rank'])
for j in range(2,1157):
    print 'j:',j
    html = urllib2.urlopen(url).read()
    url = 'http://top.chinaz.com/all/index_alexa_' + str(j) + '.html'
    soup2 = BeautifulSoup(html)
    temp = soup2.findAll('ul', attrs = {'class':'listCentent'})[0]
    l = len(temp.contents)
    c = temp.contents
    for i in range(1,l-1):
        x = c[i]
        m = {#'introduction':[x.div.next_sibling.div.next_sibling.string],
        'host':[urlprocess(x.div.a.attrs['href']) ],
        'alex':[x.div.next_sibling.div.p.a.string ],
        'baidu':[baiduprs(x.div.next_sibling.div.p.next_sibling.next_sibling.a.img.attrs['src'])],
        'pr':[PRprs(x.div.next_sibling.div.p.next_sibling.next_sibling.next_sibling.next_sibling.img.attrs['src'])],
        'Inverse chain number':[x.div.next_sibling.div.p.next_sibling.next_sibling.next_sibling.next_sibling.\
                next_sibling.next_sibling.a.string],
        'rank':[x.div.next_sibling.next_sibling.div.strong.string],
        'score':[x.div.next_sibling.next_sibling.div.span.string[3:]]}
        res = res.append(pd.DataFrame(m))
res.to_csv('D://host_rank.csv')


结果如下:



### 使用 PythonBeautifulSoup 进行网页抓取 #### 安装依赖库 为了能够顺利执行网页抓取的任务,需要先安装 `requests` 和 `beautifulsoup4` 库。可以通过 pip 工具快速完成这两个库的安装。 ```bash pip install requests beautifulsoup4 ``` #### 导入必要的模块 在编写具体的爬虫程序之前,应该导入所需的 Python 模块: ```python import requests from bs4 import BeautifulSoup ``` #### 发送 HTTP 请求获取网页内容 使用 `requests.get()` 方法向目标网站发送 GET 请求,并接收返回的内容。这里假设要访问的是某个电影列表页面。 ```python url = 'http://example.com/movies' # 替换成实际的目标网址 response = requests.get(url) if response.status_code == 200: html_content = response.text else: print(f"Failed to retrieve page, status code {response.status_code}") ``` #### 解析 HTML 文档并抽取所需信息 创建一个 BeautifulSoup 对象来解析下载下来的 HTML 字符串,并指定使用的解析器为 `"html.parser"`。接着可以根据特定标签及其属性定位到想要提取的信息节点。 ```python soup = BeautifulSoup(html_content, "html.parser") movies = [] for item in soup.find_all("div", class_="item"): try: title = item.find("span", class_="title").get_text(strip=True) rating = item.find("span", class_="rating_num").get_text(strip=True) people = item.find("div", class_="star").find_all("span")[-1].get_text(strip=True) movie_info = { "title": title, "rating": rating, "people": people } movies.append(movie_info) except AttributeError as e: continue # 如果遇到缺失字段的情况则跳过当前条目 ``` 上述代码片段展示了如何遍历所有的 `<div>` 元素(其 CSS 类名为 `item`),并且针对每一个这样的容器分别查找内部包含的影片名、评分以及参与评价的人数等细节[^4]。 #### 输出结果 最后一步就是展示收集好的数据给用户查看了。可以选择简单打印出来或是保存成其他格式如 CSV 文件供后续分析之用。 ```python for idx, movie in enumerate(movies, start=1): print(f"{idx}. Title: {movie['title']}, Rating: {movie['rating']}, People: {movie['people']}") ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值