python爬虫_1

urllib模块,内置模块

from urllib.request import urlopen

url = '网址(https://baike.baidu.com)'

html = urlopen(url).read().decode('utf-8') #如果有中文就要使用utf-8

print(html) #查看输出结果

re模块,使用正则表达式

import re

#找出第一个<title></title>标签里的内容
title1 = re.find(r'<title>(.*?)</title>',html)

#找出所有<title></title>标签里的内容
title2 = re.findall(r'<title>(.*?)</title>',html)

#查看结果
print(title1)
print(title2)
print(title2[0])

#找出所有<p></p>标签里的内容
p = re.findall(r'<p>(.*?)</p>',html,flags = re.DOTALL)
#re.DOTALL 允许多行,(.*?)为匹配内容

print(p)

使用bs4模块,比正则表达式容易使用

Python 2+

pip install beautifulsoup4

Python 3+

pip3 install beautifulsoup4
from bs4 import BeautifulSoup
from urllib.request import urlopen
import lxml

url = '网址(https://baike.baidu.com)'
html = urlopen(url).read().decode('utf-8')

soup = BeautifulSoup(html,features="lxml")#使用lxml的方式解析网页
#输出<p></p>标签的内容
print(soup.p)

a = soup.find_all('a')#找到所有a标签
#循环输出a中的网址
for i in a:
    print(i[href])

BeautifulSoup 中的 find_all() 可以添加参数

soup = BeautifulSoup(html,features='lxml')
month = soup.find_all('li',{'class':'month'})#如:<li class="month">一月</li>

print(month.get_text())#一月

img_links = soup.find_all('img',{'src':re.compile('.*?\.jpg')})
for i in img_links:
  print(i['src'])
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以帮你解决这个问题。你可以使用 Python 的第三方库 `requests` 和 `beautifulsoup4` 来爬取微博某个话题的内容数据。 首先,你需要了解微博的 URL 格式。以微博话题“Python爬虫”为例,其 URL 为:https://s.weibo.com/weibo?q=%23Python%E7%88%AC%E8%99%AB%23&Refer=top。其中,“%23”是“#”的 URL 编码,“q=”后面跟的是话题的关键词。 接下来,你可以使用 `requests` 库向该 URL 发送 GET 请求,并将响应结果的 HTML 代码解析为 `beautifulsoup4` 对象。例如: ```python import requests from bs4 import BeautifulSoup url = 'https://s.weibo.com/weibo?q=%23Python%E7%88%AC%E8%99%AB%23&Refer=top' 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'} response = requests.get(url, headers=headers) soup = BeautifulSoup(response.text, 'html.parser') ``` 然后,你可以使用 `beautifulsoup4` 的查找方法来提取微博内容数据。例如,你可以使用 `find_all` 方法找到所有的微博 div 元素,再从中提取微博的文本内容和发布时间。具体代码如下: ```python weibo_list = soup.find_all('div', class_='content') # 找到所有微博 div 元素 for weibo in weibo_list: text = weibo.find('p', class_='txt').get_text() # 提取微博文本内容 time = weibo.find('p', class_='from').find('a').get_text() # 提取微博发布时间 print(text, time) ``` 以上就是爬取微博话题“Python爬虫”内容数据的基本步骤。当然,实际应用中还需要注意反爬虫策略、数据清洗和存储等问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值