python - 如何使用 lxml 进行网页抓取?
问题描述
我想编写一个 python 脚本来获取我当前在堆栈溢出时的声誉——https://stackoverflow.com/users/14483205/raunanza ? tab=profile
这是我写的代码。
from lxml import html
import requests
page = requests.get('https://stackoverflow.com/users/14483205/raunanza?tab=profile')
tree = html.fromstring(page.content)
现在,该怎么做才能获得我的声誉。(即使在谷歌搜索之后,我也无法理解如何使用 xpath
。)
解决方案
lxml
使用and 的简单解决方案beautifulsoup
:
from lxml import html
from bs4 import BeautifulSoup
import requests
page = requests.get('https://stackoverflow.com/users/14483205/raunanza?tab=profile').text
tree = BeautifulSoup(page, 'lxml')
name = tree.find("div", {'class': 'grid--cell fw-bold'}).text
title = tree.find("div", {'class': 'grid--cell fs-title fc-dark'}).text
print("Stackoverflow reputation of {}is: {}".format(name, title))
# output: Stackoverflow reputation of Raunanza is: 3
推荐阅读
- java - 二叉树前序遍历的两种迭代解的区别
- excel - 判断excel文件是否已经打开时出错
- django - 如何在 LoginRequiredMixin、UpdateView(Django 模板)中获取当前 URL?
- vb.net - 如何对列表框中文本框输入的值求和?
- c# - 或在 .Replace() C#
- sql - 在 PostgreSQL 中导入带分隔符列表的 CSV 数据
- scala - 如何使用 Scala 在 Spark SQL 中按日期范围列表进行过滤
- sqlite - W/SQLite: (28) 未能打开
- ios - 在 ARSession 期间打开手电筒
- angular7 - 如何使用ngx-quill在角度7的quill.js工具栏中添加图像按钮?