python - 使用 Python 解析网页
问题描述
我对 Python 完全陌生,真的可以使用一些帮助。
我正在尝试解析网页并从网页中检索电子邮件地址。我尝试了很多我在网上阅读的东西,但都失败了。
我意识到,当运行 BeautifulSoup(browser.page_source) 时,它会带来源代码,但是由于某种原因,它不会带来电子邮件地址或业务配置文件。
下面是我的代码(不要判断:-))
import os, random, sys, time
from urllib.parse import urlparse
from selenium import webdriver
from bs4 import BeautifulSoup
from webdriver_manager.chrome import ChromeDriverManager
import lxml
browser = webdriver.Chrome('./chromedriver.exe')
url = ('https://www.yellowpages.co.za/search?what=accountant&where=cape+town&pg=1')
browser.get(url)
BeautifulSoup(browser.page_source)
旁注:我的目标是根据搜索条件浏览网页并解析每个页面的电子邮件地址,我已经弄清楚如何浏览网页并发送密钥,这只是我坚持的解析。您的帮助将不胜感激
解决方案
我建议你使用requests
模块到get
页面源:
from requests import get
url = 'https://www.yellowpages.co.za/search?what=accountant&where=cape+town&pg=1'
src = get(url).text # Gets the Page Source
之后,我搜索了电子邮件格式的单词并将它们添加到列表中:
src = src.split('<body>')[1] # Splits it and gets the <body> part
emails = []
for ind, char in enumerate(src):
if char == '@':
add = 1 # Count the characteres after and before
new_char = src[ind+add] # New character to add to the email
email = char # The full email (not yet)
while new_char not in '<>":':
email += new_char # Add to email
add += 1 # Readjust
new_char = src[ind + add] # Values
if '.' not in email or email.endswith('.'): # This means that the email is
continue # not fully in the page
add = 1 # Readjust
new_char = src[ind - add] # Values
while new_char not in '<>":':
email = new_char + email # Add to email
add += 1 # Readjust
new_char = src[ind - add] # Values
emails.append(email)
最后,您可以使用set
删除重复和打印电子邮件
emails = set(emails) # Remove Duplicates
print(*emails, sep='\n')
推荐阅读
- c - qsort 对动态结构的动态数组
- android - cordova emulate android 因“设备仍在连接”而失败
- signalr.client - 如何从 SignalR 客户端注销函数?
- javascript - 将动态变量中的空格格式化为谷歌地图返回函数中的连字符
- c# - 以编程方式手动将 JSON 反序列化为 C# 对象
- asp.net-web-api - 您如何从 CRM 插件调用外部 Web api?
- ios - 如何让 setInitialRoute 在不同的视图上启动我的 Flutter iOS 应用程序?
- mysql - 如何使用 SLURM 集群的远程分区连接/使用 MySQL?
- amazon-web-services - 您可以使用 AWS Appsync 查询编写器来测试 IAM 用户吗?
- angular - put方法返回未授权