133. 133
範例 05: 將高鐵時刻表的結果存成 CSV ‐
by columns
# 找出所有 td 標籤 屬性 class=column1 的內容,並存成 list
train_number = [tag.text for tag in
soup_post.find_all("td", class_="column1")]
# 找出所有 td 標籤 屬性 class=column3 的內容,並存成 list
departure = [tag.text for tag in
soup_post.find_all("td", class_="column3")]
# 找出所有 td 標籤 屬性 class=column4 的內容,並存成 list
arrival = [tag.text for tag in
soup_post.find_all("td", class_="column4")]
# 找出所有 td 標籤 屬性 class=column2 的內容,並存成 list
travel_time = [tag.text for tag in
soup_post.find_all("td", class_="column2")]
171. 檔案爬蟲 ‐ 定位節點
尋找所有 a tag 再用 regular expression 過濾 href
尋找所有裏面包含 img tag 的 a tag
尋找相同圖片而且上層是 a tag 的 img tag
171
src =
'http://140.112.115.12/exam/sites/all/modules/filefield/ic
ons/application‐pdf.png'
<a href=”...”>
</a>
<img src=”...”>
172. 檔案爬蟲 ‐ 定位節點
尋找相同圖片而且上層是 a tag 的 img tag
172
# 透過 regular expression 找到相同圖片的 img tag
images = soup.find_all('img',
{'src': re.compile('application‐pdf.png')})
for image in images:
# 透過 parent 函數尋訪 img tag 的上一層 tag
print(image.parent['href'])
225. XPath 範例
225
from selenium import webdriver
from selenium.webdriver.common.by import By
# 打開瀏覽器, 視窗最大化, 對目標網址送 request...
# 尋找網頁中所有的 p tag
p = driver.find_elements(By.XPATH, '//p')
透過 By 可以更簡單更換定位方式
226. XPath 範例
226
from selenium import webdriver
from selenium.webdriver.common.by import By
# 尋找任何一個 id = 'first' 的 tag
h2 = driver.find_element(By.XPATH,
'//*[@id="first"]')
# 尋找網頁中 id = 'second' 或 'third' 的 h2 tag
p = driver.find_elements(By.XPATH,
'//h2[@id="second"] | //h2[@id="third"]')