【问题标题】:trying to scrape url试图抓取网址
【发布时间】:2020-09-03 09:54:52
【问题描述】:

所以我试图从 Steam 上的免费游戏网站获取所有 url,但它总是返回空。我不知道我在这里做错了什么,下图显示了路径

result = requests.get("https://steamdb.info/upcoming/free/")
src = result.content
soup = BeautifulSoup(src, 'lxml')

urls = []
for td_tag in soup.find_all('td'):
    a_tag = td_tag.find('a')
    urls.append(a_tag.attrs['href'])

print(urls)

【问题讨论】:

  • 它可以检查一些标题 - 通常是“用户代理”。它可以使用 JavaScript 添加它 - requests/BeautifulSoup 无法运行 JavaScript。首先显示result.content 看看你得到了什么——也许有机器人/脚本的消息。您也可以在浏览器中关闭 JavaScript 并在浏览器中重新加载 URL 以查看可以得到什么。
  • 除了美汤还有什么更好的抓取网址的方法吗?

标签: python beautifulsoup screen-scraping


【解决方案1】:

你必须使用标题User-Agent,它不能是短的Mozilla/5.0,而是来自真实网络浏览器的完整字符串

import requests
from bs4 import BeautifulSoup

headers = {
    "User-Agent":"Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0",
}

result = requests.get("https://steamdb.info/upcoming/free/", headers=headers)
soup = BeautifulSoup(result.content, 'lxml')

#print(result.content)
urls = []
for td_tag in soup.find_all('td'):
    a_tag = td_tag.find('a')
    if a_tag:
        urls.append(a_tag.attrs['href'])

print(urls)

【讨论】:

  • 有什么特定的方法可以只从 div
    获取数据?
  • 即。使用find('div', {'id': 'live-promotions"}).find_all('a') ?
  • 顺便说一句:你也可以使用 CSS 选择 soup.select('div#live-promotions a') 。如果您使用lxml 而不是Beautifulsoup,那么您可以使用xpath,例如soup.xpath('//div[@id="live-promotions"]//a'):
  • 因为现场促销与游戏 URL 是分开的,我不得不使用 urls = soup.find('table', {'class': 'table-products table-responsive-flex table-悬停文本-左表排序'}).find_all("a")。非常感谢
猜你喜欢
相关资源
最近更新 更多
热门标签