python - 使用python在网站上的文章中搜索关键词
问题描述
我刚加入你们,距离开始学习python已经1个月了。我想用 Python ( http://aeconf.com/may2013.htm ) 从这个站点搜索关键字。
通常我手动单击视图摘要并在“关键字:”之后搜索单词。如何使用 python 自动执行此操作?我很抱歉我的英语不好:(
解决方案
你应该看看Selenium
pip install selenium
我提供了一个示例代码,您应该对此进行测试。
示例代码:
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
caps = DesiredCapabilities().CHROME
caps["pageLoadStrategy"] = "normal"
driver = webdriver.Chrome(desired_capabilities=caps, executable_path=r'C:\Users\My-PC-Name\AppData\Local\Programs\Python\Python37-32\Scripts\chromedriver.exe')
url = "http://aeconf.com/may2000.htm" #Link
driver.get(url)
links = [x.get_attribute('href') for x in driver.find_elements_by_link_text('View Abstract')]
htmls = []
for link in links:
driver.get(link)
Keyword = [y.text for y in driver.find_elements_by_xpath("//font[2]/span[@style = 'mso-bidi-font-size: 1.0pt']")]
if not Keyword: #If link is a dead link
continue
print(Keyword[0])
htmls.append(driver.page_source)
在此示例中,我将 url 更改为http://aeconf.com/may2000.htm我提供的代码主要获得了您需要的“关键字”,但在某些情况下,“关键字”的索引位置会根据在上述网址中的链接上。
“更改”链接的输出:
Fiscal decentralization; Corruption; Tax evasion.
Incentive mechanism design; Walrasian allocations; Implementation.
Debt and equity flows; Asymmetric information; Bankruptcy cost; Market failures;
Corrective taxation.
Transitory volatility; Price formation; Exogenous liquidity demand.
Investment horizon; Beta; Size; Book-to-market equity; CAPM.
G11, G13. #At This part you can see that the 'Key Words' printed are not correct
Portfolio constraints; Stochastic income; Relaxation-projection methods.
Foreign aid; Foreign borrowing; Capital accumulation.
Entrepreneurial ability; Asymmetric information; Liquidity constraints.
Contract; Human capital; Labor.
Endogenous structure of the division of labor; Dual economy; Endogenous trade policy regime.
如果我们将示例代码中的“url”变量更改为您的原始链接,那么即使第一个链接是死链接,索引位置也会发生更改的情况更多。作为一个挑战,我会让你自己弄清楚 :-) 还有更多的模块可以像 Selenium 一样做同样的事情。希望这能让您对浏览器自动化、Web Scraping 等(Web Crawler 等)产生更多兴趣。
只是提示(可能不是提示) 您只需更改“关键字”变量的索引位置即可获得所需的“关键字”。
推荐阅读
- swift - 如何在 didload 上修复圆圈上的 UIimageview
- amazon-web-services - 切换互联网连接后如何修复 aws-iot-device-sdk 断开连接行为?
- sql - 如何通过确定日期范围来显示信息
- python - 在循环中动态调用和打印函数的返回值,覆盖以前的输出
- c++ - 在 C++ 中使用构造函数参数创建向量
- asterisk - 默认情况下,星号将为数据库 cdr 表中的每个完成调用生成一个 CDR
- java - Java groupby 列并找到平均值
- javascript - 从包含文件路径的字符串列表创建树 - javascript
- django - 仅允许特定用户和超级用户编辑模型中的特定字段
- php - Laravel 5 Artisan::call 无法正常工作