在 HTML 页中搜索特定文本?
Searching through HTML pages for certain text?
我想和 python 一起玩来学习它,所以我正在做一个小项目,但其中一部分需要我在这个列表中搜索一个名字:
https://bughunter.withgoogle.com/characterlist/1
(第一个每次加一搜索名字)
所以我会 HTML 抓取它,我是 python 的新手,如果有人能给我一个如何完成这项工作的例子,我将不胜感激。
试试这个。您需要先安装 bs4 (python 3)。它将获取网站页面上所有人员的姓名:
from bs4 import BeautifulSoup as soup
import urllib.request
text=str(urllib.request.urlopen('https://bughunter.withgoogle.com/characterlist/1').read())
text=soup(text)
print(text.findAll(class_='item-list')[0].get_text())
import json
import requests
from bs4 import BeautifulSoup
URL = 'https://bughunter.withgoogle.com'
def get_page_html(page_num):
r = requests.get('{}/characterlist/{}'.format(URL, page_num))
r.raise_for_status()
return r.text
def get_page_profiles(page_html):
page_profiles = {}
soup = BeautifulSoup(page_html)
for table_cell in soup.find_all('td'):
profile_name = table_cell.find_next('h2').text
profile_url = table_cell.find_next('a')['href']
page_profiles[profile_name] = '{}{}'.format(URL, profile_url)
return page_profiles
if __name__ == '__main__':
all_profiles = {}
for page_number in range(1, 81):
current_page_html = get_page_html(page_number)
current_page_profiles = get_page_profiles(current_page_html)
all_profiles.update(current_page_profiles)
with open('google_hall_of_fame_profiles.json', 'w') as f:
json.dump(all_profiles, f, indent=2)
你的问题不清楚你希望在抓取后如何构建数据,所以我只是将配置文件保存在字典中(key/value 对作为 {profile_name: profile_url}
),然后转储结果到 json 文件。
如果有任何不清楚的地方,请告诉我!
我想和 python 一起玩来学习它,所以我正在做一个小项目,但其中一部分需要我在这个列表中搜索一个名字:
https://bughunter.withgoogle.com/characterlist/1
(第一个每次加一搜索名字)
所以我会 HTML 抓取它,我是 python 的新手,如果有人能给我一个如何完成这项工作的例子,我将不胜感激。
试试这个。您需要先安装 bs4 (python 3)。它将获取网站页面上所有人员的姓名:
from bs4 import BeautifulSoup as soup
import urllib.request
text=str(urllib.request.urlopen('https://bughunter.withgoogle.com/characterlist/1').read())
text=soup(text)
print(text.findAll(class_='item-list')[0].get_text())
import json
import requests
from bs4 import BeautifulSoup
URL = 'https://bughunter.withgoogle.com'
def get_page_html(page_num):
r = requests.get('{}/characterlist/{}'.format(URL, page_num))
r.raise_for_status()
return r.text
def get_page_profiles(page_html):
page_profiles = {}
soup = BeautifulSoup(page_html)
for table_cell in soup.find_all('td'):
profile_name = table_cell.find_next('h2').text
profile_url = table_cell.find_next('a')['href']
page_profiles[profile_name] = '{}{}'.format(URL, profile_url)
return page_profiles
if __name__ == '__main__':
all_profiles = {}
for page_number in range(1, 81):
current_page_html = get_page_html(page_number)
current_page_profiles = get_page_profiles(current_page_html)
all_profiles.update(current_page_profiles)
with open('google_hall_of_fame_profiles.json', 'w') as f:
json.dump(all_profiles, f, indent=2)
你的问题不清楚你希望在抓取后如何构建数据,所以我只是将配置文件保存在字典中(key/value 对作为 {profile_name: profile_url}
),然后转储结果到 json 文件。
如果有任何不清楚的地方,请告诉我!