用python从网页中提取一个特定单词后面的单词

2024-09-30 14:23:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个简单的web scraper脚本,从web页面中提取一个单词。我需要经常更改的单词,但后面是一个从未更改过的单词,所以我可以搜索它。在

到目前为止我的剧本是:

#!/bin/python

import requests
response = requests.get('http://vpnbook.com/freevpn')
print(response.text)

它显然打印了页面的整个HTML。但我需要的是密码:

^{pr2}$

我怎么可能只打印binbd5ar'(或其他替代品)到STOUT?在


Tags: import脚本comwebhttpgetbinresponse
3条回答
import re
re.search(r'Password: <strong>(.+)</strong>',response.text).group(1)
from bs4 import BeautifulSoup
import requests

response = requests.get('http://vpnbook.com/freevpn')
soup = BeautifulSoup(response.text, 'html.parser')
pricing = soup.find(id = 'pricing')
first_column = pricing.find('div', {'class': 'one-third'})
for li in first_column.find('ul', {'class': 'disc'}):
    if 'password' in str(li).lower():
        password = li.find('strong').text
print(password)

您可以使用regex搜索。在

“Python基于正则表达式提供了两种不同的基本操作:重新匹配()只检查字符串开头的匹配项,而搜索()检查字符串中任何位置的匹配项“ link

>>> import re
>>> x = re.search(r"Password: <strong>(?P<pass>\w+)</strong>", response.text)
>>> print x.groupdict()
{'pass': 'binbd5ar'}

相关问题 更多 >