用Appium爬取B站怎么保存图片
时间: 2023-10-10 10:13:31 浏览: 80
使用 Appium 爬取 B 站并保存图片,需要以下步骤:
1. 启动 Appium 会话,并打开 B 站 App。
```python
from appium import webdriver
desired_caps = {
'platformName': 'Android',
'deviceName': 'your_device_name',
'appPackage': 'tv.danmaku.bili',
'appActivity': 'tv.danmaku.bili.ui.splash.SplashActivity',
'noReset': True
}
driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)
```
这里将 B 站 App 的包名和启动 Activity 名称作为应用程序的信息传递给 Appium,以启动应用程序。
2. 进入 B 站 App 的某个页面,例如搜索页面。
```python
search_button = driver.find_element_by_id('tv.danmaku.bili:id/home_search')
search_button.click()
```
在这个例子中,我们通过元素的 ID 查找搜索按钮,并模拟用户点击该按钮。
3. 在搜索框中输入关键字,并点击搜索按钮。
```python
search_input = driver.find_element_by_id('tv.danmaku.bili:id/search_src_text')
search_input.send_keys('图片')
search_button = driver.find_element_by_id('tv.danmaku.bili:id/search_btn')
search_button.click()
```
这里我们通过元素的 ID 查找搜索框和搜索按钮,并分别输入关键字和点击搜索按钮。
4. 在搜索结果页面中查找图片元素,并获取图片链接。
```python
import re
pattern = re.compile(r'https://i[0-9].hdslb.com/bfs/article/(.*)\.(jpg|png|gif)')
elements = driver.find_elements_by_xpath('//img[@class="lazy-img"]')
for element in elements:
src = element.get_attribute('src')
match = pattern.search(src)
if match:
image_url = match.group(0)
# TODO: 下载图片并保存
```
在这里,我们使用正则表达式模式来匹配图片链接。然后,我们使用 `find_elements_by_xpath` 方法查找所有图片元素,并遍历它们以获取图片链接。
5. 下载图片并保存到本地。
```python
import requests
response = requests.get(image_url)
with open('image.jpg', 'wb') as f:
f.write(response.content)
```
这里我们使用 `requests` 库来下载图片,并将其保存到本地。
完整的代码示例:
```python
from appium import webdriver
import re
import requests
desired_caps = {
'platformName': 'Android',
'deviceName': 'your_device_name',
'appPackage': 'tv.danmaku.bili',
'appActivity': 'tv.danmaku.bili.ui.splash.SplashActivity',
'noReset': True
}
driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)
search_button = driver.find_element_by_id('tv.danmaku.bili:id/home_search')
search_button.click()
search_input = driver.find_element_by_id('tv.danmaku.bili:id/search_src_text')
search_input.send_keys('图片')
search_button = driver.find_element_by_id('tv.danmaku.bili:id/search_btn')
search_button.click()
pattern = re.compile(r'https://i[0-9].hdslb.com/bfs/article/(.*)\.(jpg|png|gif)')
elements = driver.find_elements_by_xpath('//img[@class="lazy-img"]')
for element in elements:
src = element.get_attribute('src')
match = pattern.search(src)
if match:
image_url = match.group(0)
response = requests.get(image_url)
with open('image.jpg', 'wb') as f:
f.write(response.content)
driver.quit()
```
请注意,此代码示例仅供学习和参考目的。在使用 Appium 爬取 B 站时,请遵守相关法律法规和网站使用条款。