python-webbrowser/requests/BeautifulSoup/selenium

webbrowser

webbrowser.open()#用於啓動瀏覽器打開一個網頁

requests

1.第三方模塊,需要安裝:pip install requests

2.作用:從web下載東西

3.requests.get() :下載一個網頁

    


將res寫入文件時要用二進制模式打開文件(爲了板胡該文本中的unicode編碼)

        f = open('lz.txt','wb')

        for chunk in res.iter_content(100000):#iter_content:返回指定長度的內容

        f.write(chunk)

BesutifulSoup

1.第三方模塊,需要安裝:pip install besutifulsoup4

2.導入時 使用 import bs4

3.創建BesutifulSoup對象

        (1)從網絡上下載網頁

                >>> import bs4

                >>> import requests

                >>> res = requests.get('https://www.baidu.com')
                >>> res.raise_for_status()

                >>> bea = bs4.BeautifulSoup(res.text)

         (2)從硬盤加載html文件

                >>> exampleFile = open('example.html')

                >>> examplesoup = bs4.BeautifulSoup(exampleFile)

4.select()#尋找元素

            >>> elems = examplesoup.select('#author')
            >>> type(elems)
            <class 'list'>
            >>> elems[0].getText()
            'Al Sweigart'
            >>> str(elems[0])
            '<span id="author">Al Sweigart</span>'
            >>> elems[0].attrs

            {'id': 'author'}

selenium

1.第三方模塊,需安裝使用

2.導入:from selenium import webdriver

3.eg:

from selenium import webdriver
browser = webdriver.Firefox()
browser.get('https://www.inventwithpython.com')
try:
    elem = browser.find_element_by_class_name('bookcover')#獲取相應內容
    print('Found <%s> element with that class name!'%(elem.tag_name))
except:
    print('not find')


linkElem = browser.find_element_by_link_text('Read Online for Free')#查找指定按鈕
linkElem.click()#模擬點擊


emailElem = browser.fing_element_by_id('Email')#根據id查找內容
emailElem.send_key('sdsds')#向找到的輸入框中添加 內容
emailElem.submit()#點擊該元素所在的表單的提交按鈕


browser.back()#返回按鈕
browser.forward()#前進按鈕
browser.refresh()#刷新
browser.quit()#關閉窗口

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章