12
2020
11

beautifulsoup find elements

https://yanwei-liu.medium.com/python%E7%88%AC%E8%9F%B2%E5%AD%B8%E7%BF%92%E7%AD%86%E8%A8%98-%E4%B8%80-beautifulsoup-1ee011df8768

e.g. 
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc, 'html.parser')
or 
soup = BeautifulSoup(resp.text, 'lxml')

soup.head.title
soup.title.string

soup.findAll("div", {"class": "stylelistrow"})

soup.find(id='abc1')
soup.find('h2') 

soup.findAll('div', attrs={'class':'image'})
soup.find_all('h2') 

# 網頁的標題文字
print(title_tag.string)

# 所有的超連結
a_tags = a_tags =      or  tags =    or   


# 搜尋 class 為 boldtext 的 b 節點
b_tag = 
print(b_tag)


# 只要其中一個 class 符合就算比對成功
p_tag = 

# 比對完整的 class 字串
p_tag = 


for tag in a_tags:  # 輸出超連結的文字
  print(tag.string)
  
or 

a_tags = soup.find("a")
print(a_tags)        

for tag in a_tags:  # 輸出超連結網址
  print(tag.get('href'))    
  print(tag.get_text())
  print(tag.getText())
  

  
  
#印出h1標籤
soup.find('h1').text                 #印出第一個h1標籤的文字
soup.find_all('h1')[0].get_text())   #印出所有h1標籤的文字
soup.find('h4',{'class':'pk'})       #印出h4標籤且class為pk的內容
soup.find(id='link2')
#find用.text顯示文字
#find用.get_text()顯示文字(資料型態須為字串格式)
#soup.find('h4')等同於soup.h4
# 根據 id 搜尋
soup.find(id='link2')
#印出段落p內文
soup.find('p').text
#搜尋多個標籤
tags = soup.find_all(["title", "p"])
#限制搜尋結果數量
tags = soup.find_all(["title", "p"], limit=2)
# 搜尋h3標籤且class為 boldtext 的內容 
soup.find_all("h3", class_="boldtext")
# 搜尋 class 為 outer-text的內容
soup.find_all(class_="outer-text")
#class用class_表示的原因是因為class是Python保留字
#輸出所有超連結URL
a_tags = soup.find_all('a')
for tag in a_tags:
  print(tag.get('href'))
#以下寫法都相同功能
soup.find_all("h4", {"class": "card-title"})
soup.find_all("h4", class_ = "card-title")
soup.find_all("h4", "card-title")
#.find().find_all()
find完element後,再針對element進行find_all()的動作
例如:soup.find("table").find_all("tr")
找到table標籤底下的所有tr標籤
注意不可寫成.find_all().find()
#實用的for loop寫法,一口氣抓出所有內容文字
[tag.text for tag in soup.find_all("tag")]








  
  
  
select()方法 [id用#、class用.、沒用#或.則視為標籤] - CSS

#查所有的CSS
bs.select('h4')      #選擇h4標籤
bs.select('#books')  #選擇id為books
bs.select('#books')  #選擇所有p標籤底下,且id為books的元素
bs.select('.PK')     #選擇class為PK
bs.select('h4.bk')   #選擇class為PK的h4標籤
bs.select('img')     #所有img標籤
bs.select("p.strikeout.body")

獲得屬性名稱的內容 .get()

for link in soup.find_all('a'):
    print(link.get('href'))


取得文字.get_text()

print(soup.get_text())
或 xxx.getText()














# 找出所有 'h' 開頭的標題文字
    titles = soup.find_all(['h1', 'h2', 'h3', 'h4', 'h5', 'h6'])
    for title in titles:
        print(title.text.strip())
# 利用 regex 找出所有 'h' 開頭的標題文字
    for title in soup.find_all(re.compile('h[1-6]')):
        print(title.text.strip())
# 找出所有 .png 結尾的圖片
    imgs = soup.find_all('img')
    for img in imgs:
        if 'src' in img.attrs:
            if img['src'].endswith('.png'):
                print(img['src'])
# 利用 regex 找出所有 .png 結尾的圖片
    for img in soup.find_all('img', {'src': re.compile('\.png$')}):
        print(img['src'])
# 找出所有 .png 結尾且含 'beginner' 的圖片
    imgs = soup.find_all('img')
    for img in imgs:
        if 'src' in img.attrs:
            if 'beginner' in img['src'] and img['src'].endswith('.png'):
                print(img['src'])
# 利用 regex 找出所有 .png 結尾且含 'beginner' 的圖片
    for img in soup.find_all('img', {'src': re.compile('beginner.*\.png$')}):
        print(img['src'])
# coding=utf-8
try:
 from selenium import webdriver
 from selenium.webdriver.common.by import By
 from selenium.webdriver.support.ui import WebDriverWait
 from selenium.webdriver.support import expected_conditions as EC

except:
 !pip install selenium
 !apt-get update
 !apt install chromium-chromedriver
 !pip install fake_useragent


import time
import pickle
import pandas as pd
import csv
import os
from google.colab import drive
from google.colab import files
from google.colab import auth

import requests
import lxml
from bs4 import BeautifulSoup
import re
import math

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException,NoSuchElementException,NoSuchFrameException
from selenium.webdriver.chrome.options import Options
from fake_useragent import UserAgent

ua = UserAgent()
usa = ua.random
print(usa)

drive.mount('/content/drive', force_remount=False)
path = "/content/drive/My Drive/"



chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
chrome_options.add_argument('--disable-blink-features=AutomationControlled')
chrome_options.add_argument(f'user-agent={usa}')
#chrome_options.add_argument('--proxy-server=http://%s' % PROXY)
wd = webdriver.Chrome('chromedriver',chrome_options=chrome_options)

wd.implicitly_wait(10)
wd.get("http://www.aastocks.com/")
title = wd.title
#print(title)

sc=wd.page_source

#print(sc)



soup = BeautifulSoup(sc, "lxml")

#print(soup.prettify())


t1=soup.find_all("div", class_="name")
t2=soup.select('.name')

t3=soup.findAll("div", {"class": "name"})

print(t1)

print(t2)

print(t3)

t=[i.get_text() for i in t1]
print(t)


« 上一篇 下一篇 »

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。