当使用python在网页上显示特定单词时通知用户

时间:2018-01-05 12:25:50

标签: python selenium web-scraping beautifulsoup lxml

我希望在网站上出现特定字时发出通知。例如,在新闻网站上如果有任何新闻更新其中包含“GST”字样,那么它应该通知我并向我提供要存储在任何文件中的新闻的详细信息。

我想继续监视它以进行更改。

是否可以使用selenium,beautifulSoup或lxml进行python?

使用以下提供的代码,如果有任何更改,我可以收到通知。但我想要显示特定单词的通知以及有关此的所有详细信息。

import urllib
import urllib2
import cookielib
import time

def fetch_html():
    # fetch logic
    cj = cookielib.CookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    resp = opener.open('www.example.com')
    data = resp.read()
    return data

def write_html(html):
    # write logic
    file = open("htmlString.txt", "w")
    file.write(html)
    file.close()
    # monitor(html)

def read_html():
    with open('htmlString.txt','r') as f:
        return f.read()

def monitor():
    write_html(fetch_html())
    while True:
        time.sleep(5)
        new_html = fetch_html()
        if new_html == read_html():
            print('Nothing has changed')
        else:
            print new_html
            print('Something has changed')
            write_html(new_html)

monitor()

谢谢。

修改 例如, 如果源代码包含

<p>The notification stipulates that manufacturers who have opted for composition scheme will now have to pay 1 percent Goods and Services Tax (GST) as against 2 percent earlier.</p>
<h1>GST council said that the e-way Bill system will have to be made ready by January 16 for trial runs.</h1>

哪个标签包含单词“GST”并未修复。我想要的是搜索具有该词的元素和标签中包含的值。

例如,

  1. 通知规定,选择合成计划的制造商现在必须支付1%的商品和服务税(GST)而不是之前的2%

  2. 消费税委员会表示,电子方式票据系统必须在1月16日之前准备好进行试运行。

  3. 谢谢

1 个答案:

答案 0 :(得分:0)

首先使用selenium,您可以找到要使用find_elements_by_xpath方法检查的元素,并使用.text从中获取文本并迭代该文本。

右键单击元素并检查,然后检查查找XPath

xpath_for_element=your path
element_to_check_for_keyword = driver.find_elements_by_xpath(xpath_for_element)
text_to_check_for_keyword=element_to_check_for_keyword.text

然后你可以遍历text_to_check_for_keyword来检查该关键字是否存在,你可以创建一个带有time.sleep的while循环来为你自己的代码设置检查时间。

修改

首先,将XPath视为HTML元素的路径, 所以同一类别下的每个元素都有相似的路径。

例如,印度时代在他们的网页上有很多部分吗?

但您可以使用*

遍历XPath 的所有部分 例如,在中间有一个带有列表的 TOP News 部分。让第6个元素的xpath是

//*[@id="pageContent"]/div[1]/div/div[6]/div[2]/ul/li[1]/ul/li[6]/a

因此,为了覆盖该部分中的每个元素,请使用

//*[@id="pageContent"]/div[1]/div/div[6]/div[2]/ul/li[1]/ul/li[*]/a

*为您提供该区域的所有元素。之后,您可以为评论,市场新闻和其他各个部分执行此操作并进行迭代。