首页 \ 问答 \ cURL没有获取URL的HTML源代码(cURL not getting HTML source of URL)

cURL没有获取URL的HTML源代码(cURL not getting HTML source of URL)

我正在尝试使用PHP创建一个简单的Web爬虫,我在获取给定URL的HTML源时遇到问题。 我目前正在使用cURL来获取源代码。

我的代码:

 $url = "http://www.nytimes.com/";

    function url_get_contents($Url) {
        if (!function_exists('curl_init')) {
            die('CURL is not installed!');
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $Url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $output = curl_exec($ch);
        if ($output === false) { die(curl_error($ch)); }
        curl_close($ch);
        return $output;
    }

    echo url_get_contents($url);
    ?>

现在没有任何回应,也没有任何错误,所以这有点神秘。 任何建议或修复将不胜感激

编辑:我补充说

if($ output === false){die(curl_error($ ch)); }

到函数的中间,它最终给了我一个错误(最后!):

无法解析主持人:www.nytimes.com

我仍然不知道问题是什么。 有任何想法吗?

谢谢


I am trying to make a simple web crawler with PHP and I am having issues getting the HTML source of a given URL. I am currently using cURL to get the source.

My code:

 $url = "http://www.nytimes.com/";

    function url_get_contents($Url) {
        if (!function_exists('curl_init')) {
            die('CURL is not installed!');
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $Url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $output = curl_exec($ch);
        if ($output === false) { die(curl_error($ch)); }
        curl_close($ch);
        return $output;
    }

    echo url_get_contents($url);
    ?>

Right now nothing gets echoed and there aren't any errors, so it is a bit of a mystery. Any suggestions or fixes will be appreciated

Edit: I added

if ($output === false) { die(curl_error($ch)); }

to the middle of the function and it ended up giving me an error (finally!):

Could not resolve host: www.nytimes.com

I still do not really know what the problem is. Any ideas?

Thanks


原文:https://stackoverflow.com/questions/31060999
更新时间:2023-01-04 15:01

最满意答案

你可以使用组合而不是继承。

想法1

PathData类可能包含对PathExtendedPathData的引用:

// encapsulate properly in your code, this is
// just a short sample
class PathData {
  public Path path;
  public ExtendedPathData data;
}

这使您可以将data成员设置为null 。 每个PathData实例的大小始终为两个引用。 当ExtendedPathData的成员数量增加时,实际的内存消耗只会增长为具有非空data PathData实例。

想法2

你可以通过使用两个实现的接口来删除更多的参考:

interface PathData {
  Path path();
  ExtendedPathData data();
}

final class NullPathData implements PathData {
  Path path;
  public Path path() { return path; }
  public ExtendedPathData data() { return null; }
}

final class ExtendedPathData implements PathData {
  Path path;
  ExtendedPathData data;
  public Path path() { return path; }
  public ExtendedPathData data() { return data; }
}

由您决定是否有两个实现真的值得代码,因为您需要一个工厂方法来决定使用哪个实现。 它是每个实例的一个 4字节参考...

更多的东西

如果ExtendedPathData不可变的,并且可能存在许多相同的实例 ,则还可以通过公开使用实例池而不是公共构造函数的静态工厂方法来将它们池化

如果你有Joshua Bloch的Effective Java ,下面是更详细的解释提示的更多参考资料(在更一般的上下文中):

  • 项目1考虑静态工厂方法而不是构造函数
  • 项目16赞成继承

You could use composition instead of inheritance.

Idea 1

A PathData class might contain a reference to a Path and a ExtendedPathData:

// encapsulate properly in your code, this is
// just a short sample
class PathData {
  public Path path;
  public ExtendedPathData data;
}

This enables you to set the data member to null. Each PathData instance has a size of constantly two references. When the number of members in ExtendedPathData grows, the actual memory consumption grows only for PathData instances that have a non-null data.

Idea 2

You could shave off one more reference by using an interface with two implementations:

interface PathData {
  Path path();
  ExtendedPathData data();
}

final class NullPathData implements PathData {
  Path path;
  public Path path() { return path; }
  public ExtendedPathData data() { return null; }
}

final class ExtendedPathData implements PathData {
  Path path;
  ExtendedPathData data;
  public Path path() { return path; }
  public ExtendedPathData data() { return data; }
}

It's up to you to decide whether having two implementations is really worth the code, as you need a factory method here to decide what implementation to use. It's one 4-byte-reference per instance...

Further stuff

If ExtendedPathData is immutable and many equal instances may exist, you could also pool them by exposing a static factory method that uses an instance pool instead of a public constructor.

In case you've got Effective Java by Joshua Bloch, here are further references explaining the tips in detail (in a more general context):

  • Item 1 Consider static factory methods instead of constructors
  • Item 16 Favor composition over inheritance

相关问答

更多
  • 这听起来像你需要鸭舌头 。 在目标c中,它可以通过使用respondsToSelector , performSelector或NSInvocation来完成。 这可以大大简化类层次结构。 It sounds like you need ducktyping. In objective c it can be accomplished by using respondsToSelector, performSelector or NSInvocation. This can simplify a class ...
  • 你可以这样做: class Square(Rectangle): def __init__(self, x): super().__init__(x, x) if self.x != self.y: raise ValueError("x and y must be equal.") 如果你想添加*args和**kwargs你可以。 但是, **kwargs ,如果你将*args和**kwargs传递给Rectangle ,这将不会产生任何 ...
  • 您需要在rootViewController重写此方法,而不是在UINavigationController 。 UIViewController *rootViewController = [[MyRootViewController alloc] init]; UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:rootViewControlle ...
  • 你可以使用组合而不是继承。 想法1 PathData类可能包含对Path和ExtendedPathData的引用: // encapsulate properly in your code, this is // just a short sample class PathData { public Path path; public ExtendedPathData data; } 这使您可以将data成员设置为null 。 每个PathData实例的大小始终为两个引用。 当ExtendedPa ...
  • 再次从数据库中获取数据。 这个公共接口是TDataSet.Refresh 。 请注意, TQuery对此的重写只会引发异常。 如果你不关心支持Refresh ,那么在这里做任何有用的事情都没有严格的要求。 Fetch the data from the database again. The public interface to this is TDataSet.Refresh. Note that TQuery's override of this just throws an exception. T ...
  • UIPageControl不会为您管理任何视图。 这是一个非常基本的控件,只显示点。 您可以使用“滑动”手势实现“页面”视图并在它们之间导航,或者您希望这样做。 有关如何将UIPageControl与两个UIViews组合在一起以在多个页面之间导航的信息,请参阅本教程 。 (直接解决问题的标题 - 你没有UIPageControl的子类) The UIPageControl does not manage any views for you. It is a very basic control that ...
  • 问题是我包括UIWindows - (void)sendEvent:(UIEvent *)事件方法,但没有调用super。 我打电话给它,一切都修好了。 The problem was I was including the UIWindows - (void)sendEvent:(UIEvent *)event method, but wasn't calling super on it. I called super on it and everything was fixed.
  • 我认为委托问题是一个红色鲱鱼:这实际上是关于战略模式与模板模式 。 “赞成组合而不是继承”是很好的建议,所以策略模式是更好的默认技术(无论你是使用对象还是委托来做你的肮脏工作),主要是因为它提供了更好的解耦。 我只使用子类化(模板模式),当有一个合适的继承关系时(根据Liskov替换原则 ),我变化的算法需要访问基类的受保护方法,我想要高度的内聚。 I think the delegate issue is a red herring: this is really about the strategy p ...
  • 你的参数错了。 OnPreExecute不带参数。 onPostExecute采用Result类型的单个参数(其中result是您选择的任何单个类型)。 它不需要可变参数。 Your parameters are wrong. OnPreExecute takes no parameters. onPostExecute takes a single parameter of type Result (where result is any single type you choose). It does ...
  • 我通过使用https://github.com/CocoaLumberjack/CocoaLumberjack/blob/master/Documentation/CustomFormatters.md中描述的CustomFormatter解决了这个问题。 基本上,我将fileLogger与自定义格式化程序相关联。 在自定义格式化程序中,每当调用DDLogError时,我都会执行所有额外步骤,例如跟踪发生错误以及在WiFi和后台上需要上载日志,添加一些自定义字符串以简化过滤等。 I solved the p ...

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。