第一个python爬虫示例:用pycharm在phthon环境下

2020-12-10  本文已影响0人  WYL_99

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

目录结构 保存的文件
上一篇 下一篇

猜你喜欢

热点阅读