Python爬虫之路-bs4和xpath

1.bs4

Beautiful Soup 4 文档

https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html

示例:爬取股票基金
import urllib
from urllib import request
from bs4 import BeautifulSoup

stockList = []

def download(url):
    headers = {
   "User-Agent": "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0);"}
    request = urllib.request.Request(url, headers=headers)  # 请求,修改,模拟http.
    data = urllib.request.urlopen(request).read()  # 打开请求,抓取数据
    
    soup = BeautifulSoup(data, "html5lib", from_encoding="gb2312")
    mytable = soup.select("#datalist")
    for line in mytable[0].find_all("tr"):
        print(line.get_text())  # 提取每一个行业
        print(line.select("td:nth-of-type(3)")[0].text) # 提取具体的某一个

if __name__ == '__main__':
    download("http://quote.stockstar.com/fund/stock.html")

存入数据库

import pymysql

# 存入数据库
def save_job(tencent_job_list):

    # 连接数据库
    db = pymysql.connect(host="127.0.0.1", port=3306, user='root', password="root",database='tencent1', charset='utf8'
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python爬虫中的bs4xpath是两种常用的数据提取工具。 bs4(Beautiful Soup 4)是一个基于Python的库,用于解析HTML和XML文档。它能够帮助我们从网页中提取数据并进行处理。bs4提供了一些简单且易于使用的方法,例如通过标签名、类名、属性等进行查找和筛选数据。 下面是一个简单的使用bs4进行数据提取的例子: ```python from bs4 import BeautifulSoup import requests # 发送HTTP请求获取页面内容 url = "http://example.com" response = requests.get(url) html_content = response.content # 使用bs4解析页面内容 soup = BeautifulSoup(html_content, 'html.parser') # 提取数据 title = soup.title.text print("网页标题:", title) # 查找某个标签并获取其文本内容 h1 = soup.find("h1") print("h1标签内容:", h1.text) # 查找所有的链接并输出链接文本和URL links = soup.find_all("a") for link in links: print("链接文本:", link.text) print("链接URL:", link["href"]) ``` 另一方面,XPath是一种用于选择XML文档中节点的语言。在爬虫中,我们可以使用XPath来从HTML或XML文档中提取数据。XPath提供了强大且灵活的选择器,可以使用路径表达式来定位节点。 下面是一个使用XPath进行数据提取的示例: ```python import requests from lxml import etree # 发送HTTP请求获取页面内容 url = "http://example.com" response = requests.get(url) html_content = response.content # 使用lxml解析页面内容 tree = etree.HTML(html_content) # 提取数据 title = tree.xpath("//title/text()")[0] print("网页标题:", title) # 查找某个标签并获取其文本内容 h1 = tree.xpath("//h1/text()")[0] print("h1标签内容:", h1) # 查找所有的链接并输出链接文本和URL links = tree.xpath("//a") for link in links: link_text = link.xpath("text()")[0] link_url = link.xpath("@href")[0] print("链接文本:", link_text) print("链接URL:", link_url) ``` 以上就是使用bs4XPath进行数据提取的示例代码。希望能帮助到你!如有需要,请随时追问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值