Ai
1 Star 0 Fork 2

open/Python-100-Days

forked from 阿甘/Python-100-Days 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
example03.py 960 Bytes
一键复制 编辑 原始数据 按行查看 历史
jackfrued 提交于 2018-05-28 17:31 +08:00 . 更新了爬虫第1天代码
from bs4 import BeautifulSoup
import requests
import re
def main():
# 通过requests第三方库的get方法获取页面
resp = requests.get('http://sports.sohu.com/nba_a.shtml')
# 对响应的字节串(bytes)进行解码操作(搜狐的部分页面使用了GBK编码)
html = resp.content.decode('gbk')
# 创建BeautifulSoup对象来解析页面(相当于JavaScript的DOM)
bs = BeautifulSoup(html, 'lxml')
# 通过CSS选择器语法查找元素并通过循环进行处理
# for elem in bs.find_all(lambda x: 'test' in x.attrs):
for elem in bs.select('a[test]'):
# 通过attrs属性(字典)获取元素的属性值
link_url = elem.attrs['href']
resp = requests.get(link_url)
bs_sub = BeautifulSoup(resp.text, 'lxml')
# 使用正则表达式对获取的数据做进一步的处理
print(re.sub(r'[\r\n]', '', bs_sub.find('h1').text))
if __name__ == '__main__':
main()
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
HTML
1
https://gitee.com/netb/Python-100-Days.git
git@gitee.com:netb/Python-100-Days.git
netb
Python-100-Days
Python-100-Days
master

搜索帮助