地址:aHR0cHM6Ly9zcGlkZXJidWYuY24vd2ViLXNjcmFwaW5nLXByYWN0aWNlL3NjcmFwaW5nLWNzcy1jb25mdXNlLW9mZnNldA==
整体界面:
f12查看响应 发现 腾讯 两个字倒了
输出查看数据:
把第二个字放到最前面进行拼接:
然后是 企业估值 混淆:
完整代码:
import requests
from lxml import etree
url = 'https://www.spiderbuf.cn/web-scraping-practice/scraping-css-confuse-offset'
myheaders = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.6099.200 Safari/537.36'
}
response = requests.get(url, headers=myheaders)
html_content = response.text
tree = etree.HTML(html_content)
divs = tree.xpath('//div[@class ="container"]/div/div')
for div in divs:
# 提取当前数据项下的 h2 标签
hnodes = div.xpath('./h2')
temp = hnodes[0].xpath('string(.)')
# 对公司名称进行字符偏移处理(CSS 字符混淆,手动修复顺序)
s0 = temp[1:2] + temp[0:1] + temp[2:]
print(s0)
pnodes = div.xpath('./p')
# 提取第一个 p 标签的内容(排名信息)
s1 = pnodes[0].text
# 提取第二个 p 标签的内容(企业估值),并去掉前缀“企业估值(亿元):”
temp = pnodes[1].xpath('string(.)').replace('企业估值(亿元):', '')
# 对企业估值进行字符偏移处理(CSS 字符混淆,手动修复顺序)
s2 = temp[1:2] + temp[0:1] + temp[2:]
# 输出修复后的企业估值
print(s2)
# 提取第三个 p 标签的内容(CEO 信息)
s3 = pnodes[2].text
# 输出 CEO 信息
print(s3)
# 提取第四个 p 标签的内容(行业信息)
s4 = pnodes[3].text
# 输出行业信息
print(s4)
# 将提取的信息拼接成一行数据,以 '|' 分隔字段
s = s0 + '|' + s1.replace('排名:', '') + '|' + s2.replace('企业估值(亿元):', '') + '|' \
+ s3.replace('CEO:', '') + '|' + s4.replace('行业:', '') + '\n'
# 输出格式化后的数据行
print(s)
最终输出结果: