python写一个简单的爬虫样例

296次阅读
没有评论

用pycharm在phthon环境下做的一个简单爬虫

Python版本: Python3.7

运行平台: Windows

IED: pyCharm 2020.3

import requests

from lxml import etree

from bs4 import BeautifulSoup

import re

import urllib.request

def getArtical():

url = 'http://www.cntour.cn/'

# 用 GET 方式获取数据; 将获取到的数据存到 strhtml 变量中

strhtml = requests.get(url)

# strhtml.text 表示网页源码

print(strhtml.text)

soup = BeautifulSoup(strhtml.text, 'lxml')

# data = soup.select('#main > div > div.mtop.firstMod.clearfix > div.centerBox > ul.newsList > li > a')

# 获取所有a标签

data = soup.find_all('a')

print(data)

with open('./中国旅游网.txt', 'w', encoding='utf-8') as f:

# 遍历获取的所有a标签

for item in data:

# 提取标签的正文用 get_text() 方法

title = item.get_text()

# 提取标签中的 href 属性用 get() 方法,在括号中指定要提取的属性数据,即 get('href')。

link = item.get('href')

# 获取链接末尾的id

id = re.findall('\d+', item.get('href'))

print(result)

# 不知道为什么link最后一个打印出来是none,可能是href属性里面是空的。

# 加上link的判断,解决报错,虽然报错,但是还是保存成功了……没加之前报错 TypeError: write() argument must be str, not None

if(link):

# 保存到文件

f.write('标题:'+title+' , ')

f.write('链接:'+link)

f.write('\n')

# 调用函数

getArtical()

python写一个简单的爬虫样例

目录结构

python写一个简单的爬虫样例

python写一个简单的爬虫样例

保存的文件

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:Python教程2022-10-28发表,共计1069字。
新手QQ群:570568346,欢迎进群讨论 Python51学习