用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() 方法