首页 > 解决方案 > 如何使用 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
。)

标签: pythonweb-scrapinglxml.html

解决方案


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

推荐阅读