【问题标题】:file_get_contents returns 403 forbidden with user agent - PHPfile_get_contents 返回 403 禁止用户代理 - PHP
【发布时间】:2022-06-11 05:00:26
【问题描述】:

我只是想从这个产品页面获取标题,但是它一直显示 403 禁止错误。

警告:file_get_contents(https://www.brownsfashion.com/uk/shopping/jem-18k-yellow-gold-octogone-double-paved-ring-17648795):打开流失败:HTTP 请求失败! HTTP/1.1 403 Forbidden in /Applications/AMPPS/www/get_prod.php on line 13"

我尝试在其中添加用户代理,但似乎仍然无法正常工作。也许是不可能的。

代码如下:

        <?php
include('simple_html_dom.php');

$context = stream_context_create(
    array(
        "http" => array(
            "header" => "User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36"
        )
    )
);

echo file_get_contents("https://www.brownsfashion.com/uk/shopping/jem-18k-yellow-gold-octogone-double-paved-ring-17648795", false, $context);
?>

【问题讨论】:

  • 该站点状态 you are not allowed to 'scrape' content 的 TOS。也许你的IP被列入黑名单
  • @user3783243 我重现了错误,所以它看起来不像是IP黑名单。
  • 但是由于该网站不允许网页抓取,您不应该浪费时间尝试解决这个问题。
  • 我不会使用 PHP 进行内容抓取:您如何处理由 javascript 广告 DOM 注入/创建的内容?

标签: php web screen-scraping user-agent


【解决方案1】:

本网站有 3 个反爬虫系统:

  1. 有风险。
  2. 福特。
  3. Cloudflare。

它们用于防止 DoS/DDoS 攻击,抓取任务......基本上你不能通过简单的请求轻松抓取它们。

要绕过它们,您需要模拟/使用真实的浏览器。您可以使用seleniumplaywright
我将向您展示一个使用 playwright 和 python 抓取该网站的示例。

from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.webkit.launch(headless=True)
    baseurl = "https://www.brownsfashion.com/uk/shopping/jem-18k-yellow-gold-octogone-double-paved-ring-17648795"
    page = browser.new_page()
    page.goto(baseurl)
    title = page.wait_for_selector("//a[@data-test='product-brand']")
    name = page.wait_for_selector("//span[@data-test='product-name']")
    price = page.wait_for_selector("//span[@data-test='product-price']")
    print("Title: " + title.text_content())
    print("Name: " + name.text_content())
    print("Price: " + price.text_content())
    browser.close()

希望能帮到你。

【讨论】:

    猜你喜欢
    • 2011-05-31
    • 1970-01-01
    • 1970-01-01
    • 2020-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-18
    相关资源
    最近更新 更多